mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge pull request #9888 from dotCooCoo/feat/ai-inline-placed-eps
.ai import: a placed EPS file whose bytes the editing data includes opens as a placed document
This commit is contained in:
21 files changed
+1054
-51
No files matched your search
@@ -380,6 +380,28 @@ pub type Loader = fn(&PlacedDocument, &[u8]) -> Option<(Document, Node, Rect)>;
|
||||
|
||||
static LOADER: OnceLock<Loader> = OnceLock::new();
|
||||
|
||||
std::thread_local! {
|
||||
/// Open checks use previews rather than loading placed documents for drawing.
|
||||
static PREVIEWS_ONLY: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Restores whether only previews are used when an open check ends, including on unwind.
|
||||
struct PreviewsOnly(bool);
|
||||
|
||||
impl Drop for PreviewsOnly {
|
||||
fn drop(&mut self) {
|
||||
PREVIEWS_ONLY.with(|p| p.set(self.0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Run an open check using placed documents' previews instead of loading their art on this
|
||||
/// thread. Nested checks keep the scope active until the outer check ends. This prevents an
|
||||
/// open check and drawing from recursively loading each other's nested files.
|
||||
pub fn with_previews<T>(check: impl FnOnce() -> T) -> T {
|
||||
let _scope = PreviewsOnly(PREVIEWS_ONLY.with(|p| p.replace(true)));
|
||||
check()
|
||||
}
|
||||
|
||||
/// Register how files are read (the first registration stays).
|
||||
pub fn set_loader(l: Loader) {
|
||||
// Already set: the same loader, registered by another session.
|
||||
@@ -454,8 +476,12 @@ impl Cache {
|
||||
}
|
||||
|
||||
/// `p`'s file (`bytes`) read, from the cache when it was read already: what the renderer draws a
|
||||
/// placed document from. `None` when it can't be read (or no loader is registered).
|
||||
/// placed document from. `None` when it can't be read, no loader is registered, or an open check
|
||||
/// uses [`with_previews`].
|
||||
pub fn read(p: &PlacedDocument, bytes: &Arc<Vec<u8>>) -> Option<Arc<ReadDocument>> {
|
||||
if PREVIEWS_ONLY.with(std::cell::Cell::get) {
|
||||
return None;
|
||||
}
|
||||
if let Some(e) = cache().get(&p.key, false, Some(bytes)) {
|
||||
return Some(e);
|
||||
}
|
||||
@@ -738,6 +764,22 @@ mod tests {
|
||||
Some((d, Node::new(NodeId(0), NodeKind::Group { children, clip: false }), Rect::new(0.0, 0.0, 40.0, 20.0)))
|
||||
}
|
||||
|
||||
/// Nested open checks skip both new and cached art, and restore ordinary reads afterward.
|
||||
#[test]
|
||||
fn open_checks_leave_placed_documents_for_drawing_afterward() {
|
||||
set_loader(stub_loader);
|
||||
let p = placed("open-check-1");
|
||||
let bytes = Arc::new(b"leaf".to_vec());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
with_previews(|| {
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
with_previews(|| assert!(read(&p, &bytes).is_none()));
|
||||
assert!(read(&p, &bytes).is_none());
|
||||
});
|
||||
assert!(read(&p, &bytes).is_some());
|
||||
}
|
||||
|
||||
/// A color-masked image in a placed document's art keeps its masked pixels under the prefixed
|
||||
/// names its resources get.
|
||||
#[test]
|
||||
|
||||
@@ -122,7 +122,8 @@ proptest = { workspace = true }
|
||||
vectorcraft-text = { workspace = true, features = ["test-fonts"] }
|
||||
# How many times an open reads a PDF, and the work its import takes.
|
||||
vectorcraft-pdf = { workspace = true, features = ["read-count"] }
|
||||
# The work `.ai` blends take to be checked and made live.
|
||||
# The work `.ai` blends take to be checked and made live, and how many included EPS open checks
|
||||
# an open performs.
|
||||
vectorcraft-eps = { workspace = true, features = ["work-count"] }
|
||||
# How many times the symbol list is read to find symbols by name, and how many objects are
|
||||
# measured against locked artboards.
|
||||
|
||||
@@ -106,7 +106,7 @@ type PlacedPages = Vec<(u32, bool, vectorcraft_doc::PageBox)>;
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Tests: how many placed PDF or `.ai` pages [`page_fonts`] read on this thread.
|
||||
/// Tests: how many placed PDF, `.ai` or EPS pages [`page_fonts`] read on this thread.
|
||||
pub(crate) static PAGES_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Tests: how many linked `.vectorcraft` files had their preview and PDF read on this thread,
|
||||
/// to keep them in the rewritten copy.
|
||||
@@ -196,16 +196,41 @@ fn check_carried_folder(name: &str, bytes: &[u8]) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
|
||||
/// none for other files.
|
||||
/// The fonts of the type on `pages` of the PDF, `.ai` or EPS file `name` (`bytes`, found at
|
||||
/// `path`), and on the placed documents that art holds (an EPS file whose bytes a legacy `.ai` or
|
||||
/// EPS file includes), [`MAX_NESTED_PAGES`] deep; none for other files.
|
||||
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
|
||||
nested_page_fonts(name, bytes, path, pages, 0)
|
||||
}
|
||||
|
||||
/// The most placed documents [`page_fonts`] reads inside one another.
|
||||
const MAX_NESTED_PAGES: usize = 8;
|
||||
|
||||
/// [`page_fonts`], `depth` placed documents in.
|
||||
fn nested_page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages, depth: usize) -> BTreeSet<super::fonts::UsedFont> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
if super::place::document::is_pdf(name, bytes) {
|
||||
if super::place::document::is_pdf(name, bytes) || super::place::document::is_postscript(bytes) {
|
||||
for &(page, bounding, page_box) in pages {
|
||||
#[cfg(test)]
|
||||
PAGES_READ.with(|c| c.set(c.get() + 1));
|
||||
if let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) {
|
||||
fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes));
|
||||
let Ok(a) = super::place::document::document_art(name, bytes, Some(path), page, bounding, page_box, C) else { continue };
|
||||
fonts.extend(super::fonts::art_fonts(&a.doc, &a.nodes));
|
||||
if depth + 1 >= MAX_NESTED_PAGES {
|
||||
continue;
|
||||
}
|
||||
let mut inner = Vec::new();
|
||||
let patterns = a.doc.patterns.iter().flat_map(|p| p.art.iter().map(|n| &**n));
|
||||
for n in a.doc.layers.iter().map(|l| &**l).chain(a.doc.symbols.iter().map(|s| &*s.art)).chain(patterns).chain(&a.nodes) {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| {
|
||||
if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind {
|
||||
inner.push(p.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
for p in inner {
|
||||
// Only the bytes the art keeps: its own file isn't looked for.
|
||||
let Some(blob) = a.doc.images.get(&p.key).filter(|b| !b.is_proxy()) else { continue };
|
||||
fonts.extend(nested_page_fonts(p.link.name(), &blob.bytes, &p.link.path, &vec![(p.page(), p.bounding, p.page_box)], depth + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,7 +344,7 @@ impl<'a> Collector<'a> {
|
||||
// Different linked documents can reuse the same stale absolute path yet
|
||||
// resolve it to distinct local assets. Keep a mapping per document.
|
||||
let mut local = BTreeMap::<String, Copied>::new();
|
||||
// The fonts of the type on the PDF and `.ai` pages placed linked.
|
||||
// The fonts of the type on the PDF, `.ai` and EPS pages placed linked.
|
||||
let mut placed_fonts = BTreeSet::new();
|
||||
let mut placed = BTreeMap::<String, PlacedPages>::new();
|
||||
let linked_files = |doc: &Document| match lookup {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Placed documents (`file.place` of a VectorCraft document, a PDF, a `.ai` file or an EPS file
|
||||
//! from a file, with `link`): one locked object showing an artboard of the document, a page of the
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`].
|
||||
//! PDF or the EPS file's art, a [`PlacedDocument`]. An EPS file whose bytes a `.ai` file's editing
|
||||
//! data includes opens as one too, read from those bytes.
|
||||
//!
|
||||
//! The object keeps the file's bytes (in the document's images, like image data) and the link; the
|
||||
//! art it shows is read from them the way placing the file without Link reads it
|
||||
@@ -223,6 +224,27 @@ impl Drop for Reading {
|
||||
}
|
||||
}
|
||||
|
||||
std::thread_local! {
|
||||
/// How many placed documents [`read_document`] is reading inside one another on this thread.
|
||||
static DRAWING: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// A placed document being read for drawing ([`DRAWING`]): the count goes down when this goes.
|
||||
struct Drawing;
|
||||
|
||||
impl Drawing {
|
||||
/// `None` when [`MAX_NESTED_READS`] are being read.
|
||||
fn enter() -> Option<Self> {
|
||||
DRAWING.with(|d| (d.get() < MAX_NESTED_READS).then(|| d.set(d.get() + 1))).map(|()| Drawing)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Drawing {
|
||||
fn drop(&mut self) {
|
||||
DRAWING.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
}
|
||||
}
|
||||
|
||||
/// `nodes` as one group, clipped to `clip` (its own ids: what drawing reads).
|
||||
fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
|
||||
let mut children: Vec<Arc<Node>> = nodes.into_iter().map(Arc::new).collect();
|
||||
@@ -234,11 +256,22 @@ fn group(nodes: Vec<Node>, clip: Option<Rect>) -> Node {
|
||||
|
||||
/// `p`'s file (`bytes`) read as the art it shows: how the document model reads placed documents
|
||||
/// ([`vectorcraft_doc::placed_document::set_loader`]).
|
||||
/// `None` past [`MAX_NESTED_READS`] placed documents read inside one another: opening a file can
|
||||
/// draw the placed documents in it, whose files can place others.
|
||||
pub(crate) fn read_document(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
let _drawing = Drawing::enter()?;
|
||||
#[cfg(test)]
|
||||
DOCUMENT_READS.with(|n| n.set(n.get() + 1));
|
||||
let a = document_art(p.link.name(), bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, "draw").ok()?;
|
||||
Some((a.doc, group(a.nodes, a.clip), a.frame))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
std::thread_local! {
|
||||
/// Placed documents read for drawing on this thread, for tests that count work.
|
||||
pub(crate) static DOCUMENT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// `p`'s file read again, while it is the file it was read from (how the document model gets it
|
||||
/// when only the preview is stored, [`vectorcraft_doc::placed_document::set_file_reader`]).
|
||||
pub(crate) fn read_file_again(p: &PlacedDocument) -> Option<Vec<u8>> {
|
||||
|
||||
@@ -1115,6 +1115,82 @@ fn package_reads_no_placed_pdf_page_without_copy_fonts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Copy Fonts on, Package reads the type of a placed EPS file whose bytes a `.ai` file's
|
||||
/// editing data included, as it reads a placed PDF page's.
|
||||
#[test]
|
||||
fn package_reads_a_placed_eps_files_type_for_copy_fonts() {
|
||||
use cmd::package::PAGES_READ;
|
||||
use vectorcraft_testkit::ai;
|
||||
let dir = Folder::new("package-placed-eps-fonts");
|
||||
let eps =
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Helvetica findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n";
|
||||
let src = dir.file("art/shape.eps");
|
||||
write(&src, eps.as_bytes());
|
||||
let src = src.replace('\\', "/");
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n({src})`\n%%BeginDocument: {src}\n{eps}\n%%EndDocument\n~\n%AI5_EndPlace\n"
|
||||
);
|
||||
let doc_path = dir.file("poster.ai");
|
||||
let page = "BT /F1 12 Tf 10 50 Td (Saved without its PDF part) Tj ET";
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place)).as_bytes(), page));
|
||||
let mut s = session();
|
||||
open(&mut s, &doc_path);
|
||||
let mut placed = 0;
|
||||
s.doc().unwrap().doc.visit_placed(|_, _| placed += 1);
|
||||
assert_eq!(placed, 1);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let before = PAGES_READ.with(std::cell::Cell::get);
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(PAGES_READ.with(std::cell::Cell::get) - before, 1, "{r}");
|
||||
let listed = |r: &Value| r["fonts"].as_u64().unwrap_or(0) + r["skippedFonts"].as_array().map_or(0, |a| a.len() as u64);
|
||||
assert_eq!(listed(&r), 1, "the type's font: {r}");
|
||||
|
||||
// Type only in an EPS file that the placed one, a legacy-format file, includes in turn.
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let typed =
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n/Courier findfont 12 scalefont setfont 10 10 moveto (Hi) show\n%%EOF\n";
|
||||
let inner = format!("[1 0 0 1 0 0] 0 0 60 60 (inner.eps) `\n%%BeginDocument: inner.eps\n{typed}%%EndDocument\n~\n");
|
||||
let outer = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n\
|
||||
%%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\
|
||||
{inner}LB\n%AI5_EndLayer--\nshowpage\n%%EOF\n"
|
||||
);
|
||||
write(&dir.file("art/shape.eps"), outer.as_bytes());
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page));
|
||||
open(&mut s, &doc_path);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out2"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(listed(&r), 1, "the inner file's font: {r}");
|
||||
|
||||
// The included file is only in a pattern definition, outside the page's nodes.
|
||||
let pattern = format!("%AI3_BeginPattern: (Type)\n(Type) 0 0 60 60\n0 A\n0 Xw\n{inner}E\n%AI3_EndPattern\n");
|
||||
let outer = outer.replace(&inner, "").replace("%AI5_BeginLayer", &format!("{pattern}%AI5_BeginLayer"));
|
||||
let a = cmd::place::document::document_art("shape.eps", outer.as_bytes(), Some(&src), 1, false, vectorcraft_doc::PageBox::Crop, "t").unwrap();
|
||||
let pattern = a.doc.pattern("Type").expect("the pattern definition is read");
|
||||
let mut placements = 0;
|
||||
for n in &pattern.art {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| {
|
||||
assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::Text(_)), "the type is only in the included file");
|
||||
if let vectorcraft_doc::NodeKind::PlacedDocument(p) = &n.kind {
|
||||
placements += 1;
|
||||
let blob = &a.doc.images[&p.key];
|
||||
assert!(!blob.is_proxy());
|
||||
assert_eq!(blob.bytes.as_slice(), typed.as_bytes());
|
||||
}
|
||||
});
|
||||
}
|
||||
assert_eq!(placements, 1, "the pattern holds the included file");
|
||||
for n in &a.nodes {
|
||||
vectorcraft_doc::swatches::walk_with_masks(n, &mut |n| assert!(!matches!(n.kind, vectorcraft_doc::NodeKind::PlacedDocument(_))));
|
||||
}
|
||||
write(&dir.file("art/shape.eps"), outer.as_bytes());
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, &outer))).as_bytes(), page));
|
||||
open(&mut s, &doc_path);
|
||||
save(&mut s, &dir.file("poster.vectorcraft"));
|
||||
let r = run(&mut s, "file.package", json!({"folder": dir.file("out3"), "copyLinks": false, "copyFonts": true}));
|
||||
assert_eq!(listed(&r), 1, "the pattern's included file's font: {r}");
|
||||
}
|
||||
|
||||
/// `dir/art/badge.ai`, saved without its PDF part, its art placing each of `pics` (600 × 300 px,
|
||||
/// with a 2×1 preview) → its path.
|
||||
fn ai_placing(dir: &Folder, pics: &[&str]) -> String {
|
||||
|
||||
@@ -934,6 +934,127 @@ fn an_ai_file_that_places_itself_opens() {
|
||||
assert_eq!(found, [at], "{r}");
|
||||
}
|
||||
|
||||
/// A placed EPS file whose bytes a `.ai` file's editing data includes (between `%%BeginDocument:`
|
||||
/// and `%%EndDocument`) opens as a placed document of those bytes: it draws its art with its file
|
||||
/// missing, and its file found unchanged is neither missing nor modified. A native save keeps the
|
||||
/// bytes, so the copy reopens and draws without the file.
|
||||
#[test]
|
||||
fn a_placed_eps_file_included_in_an_ai_files_editing_data_draws_without_its_file() {
|
||||
use vectorcraft_testkit::ai;
|
||||
let dir = Folder::new("placed-eps-in-ai");
|
||||
// The file draws red and the page blue, so each check shows which one drew.
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor\n0 0 60 60 rectfill\n%%EOF\n";
|
||||
let (red, blue) = ([255, 0, 0], [0, 0, 255]);
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 1 20 20] 0 0 60 60 4 4 0\n(/no/such/folder/src/shape.eps)`\n\
|
||||
%%BeginDocument: /no/such/folder/src/shape.eps\n{eps}\n%%EndDocument\n%AI17_Begin_Content_if_version_gt:24 12\n\
|
||||
%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"
|
||||
);
|
||||
let doc_path = dir.file("poster.ai");
|
||||
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &place));
|
||||
write(&doc_path, &ai::ai(data.as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
let shown = |s: &Session| {
|
||||
let img = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, Rect::new(0.0, 0.0, 100.0, 100.0), 1.0, true);
|
||||
let [r, g, b, _] = img.pixel(50, 50);
|
||||
[r, g, b]
|
||||
};
|
||||
let one = |s: &Session| {
|
||||
let d = &s.doc().unwrap().doc;
|
||||
let mut found = vec![];
|
||||
d.visit_placed(|n, p| found.push((n.id, p.clone())));
|
||||
let [(id, p)] = &found[..] else { panic!("one placed document: {found:?}") };
|
||||
(*id, p.clone(), d.images[&p.key].clone())
|
||||
};
|
||||
let mut s = session();
|
||||
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!(r["missingLinks"][0]["name"].as_str(), Some("shape.eps"), "{r}");
|
||||
let (id, p, blob) = one(&s);
|
||||
assert_eq!((blob.bytes.as_slice(), blob.mime.as_str()), (eps.as_bytes(), "application/postscript"));
|
||||
assert_eq!(p.link.relative.as_deref(), Some("src/shape.eps"));
|
||||
let at = bounds(&s, id);
|
||||
assert!((at.x0 - 20.0).abs() < 0.01 && (at.y0 - 20.0).abs() < 0.01 && (at.width() - 60.0).abs() < 0.01, "{at:?}");
|
||||
assert!(near(shown(&s), red), "its art draws: {:?}", shown(&s));
|
||||
|
||||
write(&dir.file("src/shape.eps"), eps.as_bytes());
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert_eq!((r["missingLinks"].clone(), r["modifiedLinks"].clone()), (json!([]), json!([])), "{r}");
|
||||
assert!(near(shown(&s), red));
|
||||
|
||||
let copy = dir.file("copy.vectorcraft");
|
||||
save(&mut s, ©);
|
||||
std::fs::remove_file(dir.file("src/shape.eps")).unwrap();
|
||||
open(&mut s, ©);
|
||||
let (_, _, blob) = one(&s);
|
||||
assert_eq!(blob.bytes.as_slice(), eps.as_bytes(), "the bytes are saved");
|
||||
assert!(near(shown(&s), red), "and draw: {:?}", shown(&s));
|
||||
|
||||
// A file named as PostScript of another kind, or with a name that doesn't say, draws the same.
|
||||
for name in ["shape.ps", "shape", "shape.dat"] {
|
||||
let named = place.replace("shape.eps", name);
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &named)).as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
open(&mut s, &doc_path);
|
||||
let (_, p, blob) = one(&s);
|
||||
assert_eq!((p.link.name(), blob.mime.as_str()), (name, "application/postscript"));
|
||||
assert!(near(shown(&s), red), "{name} draws: {:?}", shown(&s));
|
||||
}
|
||||
|
||||
// Bytes that can't be read leave the placed file unread: the file is read from its PDF part,
|
||||
// and the object comes in as what the page draws there.
|
||||
let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
write(&doc_path, &ai::ai(ai::editing_data(200.0, 100.0, &ai::layer("Art", &place.replace(eps, broken))).as_bytes(), "0 0 1 rg 20 20 60 60 re f"));
|
||||
let r = open(&mut s, &doc_path);
|
||||
assert!(near(shown(&s), blue), "the page's art: {:?} {r}", shown(&s));
|
||||
}
|
||||
|
||||
/// A synthetic EPS file that includes another placed EPS file, `depth` levels deep.
|
||||
fn nested_included_eps(depth: usize) -> String {
|
||||
let prolog = "/Lb {10 {pop} repeat} def /Ln {pop} def /LB {} def /A {pop} def /` {gsave 5 {pop} repeat concat} def /~ {grestore} def";
|
||||
let mut eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor\n10 20 40 30 rectfill\n%%EOF\n".to_string();
|
||||
for _ in 0..depth {
|
||||
eps = format!(
|
||||
"%!PS-Adobe-3.0 EPSF-3.0\n%%Creator: VectorCraft\n%AI5_FileFormat 4.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n\
|
||||
%%BeginProlog\n{prolog}\n%%EndProlog\n%AI5_BeginLayer\n1 1 1 1 0 0 0 79 128 255 Lb\n(Back) Ln\n0 A\n\
|
||||
[1 0 0 1 0 0] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\nLB\n%AI5_EndLayer--\nshowpage\n%%EOF\n"
|
||||
);
|
||||
}
|
||||
eps
|
||||
}
|
||||
|
||||
/// Open checks and drawing must not recursively multiply each other's work.
|
||||
#[test]
|
||||
fn placed_eps_files_included_open_work_is_bounded() {
|
||||
let dir = Folder::new("placed-eps-open-work");
|
||||
let path = dir.file("deep.eps");
|
||||
write(&path, nested_included_eps(12).as_bytes());
|
||||
let mut s = session();
|
||||
let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get);
|
||||
let checks = vectorcraft_eps::included_eps_reads();
|
||||
open(&mut s, &path);
|
||||
let drawings = crate::cmd::place::document::DOCUMENT_READS.with(std::cell::Cell::get) - drawings;
|
||||
let checks = vectorcraft_eps::included_eps_reads() - checks;
|
||||
eprintln!("included EPS work: {drawings} drawing reads, {checks} open checks");
|
||||
// At most 8 drawing loads, each with at most 8 parses for checks, plus the outer import's 8.
|
||||
// Repeated structural reads share completed checks within each chain.
|
||||
assert!(drawings <= 8, "{drawings} drawing reads, {checks} open checks");
|
||||
assert!(checks <= 8 * 8 + 8, "{drawings} drawing reads, {checks} open checks");
|
||||
assert!(drawings > 0 && checks > 0, "both read paths were exercised");
|
||||
}
|
||||
|
||||
/// A legacy-format file (version 7 specification §16) placing an EPS file whose bytes it includes,
|
||||
/// which is such a file in turn, 300 deep: it opens, reading a bounded number of them.
|
||||
#[test]
|
||||
fn placed_eps_files_included_300_deep_open() {
|
||||
let dir = Folder::new("placed-eps-300-deep");
|
||||
let path = dir.file("deep.eps");
|
||||
write(&path, nested_included_eps(300).as_bytes());
|
||||
let mut s = session();
|
||||
open(&mut s, &path);
|
||||
let mut placed = 0;
|
||||
s.doc().unwrap().doc.visit_placed(|_, _| placed += 1);
|
||||
assert_eq!(placed, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pdf_compatible_ai_file_places_linked_like_a_pdf() {
|
||||
let dir = Folder::new("placed-ai-linked");
|
||||
|
||||
@@ -4950,6 +4950,37 @@ proptest! {
|
||||
survive("hostile .ai images and placed files", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, false, 1.0).0))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose placed EPS files have their bytes included between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` (one on `%_` lines, one with a nested document and counted data in it),
|
||||
/// damaged, opened and drawn: their bytes are read as an EPS file when drawn.
|
||||
#[test]
|
||||
fn ai_placed_eps_files_with_included_bytes_never_panic(
|
||||
cut in 0usize..4_000,
|
||||
edits in prop::collection::vec((0usize..4_000, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '[', ']', '%', '_', '`', '~', 'E', 'D'])), 0..12),
|
||||
) {
|
||||
use vectorcraft_testkit::ai;
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 40\n%%EndComments\n0 0 1 setrgbcolor\n0 0 60 40 rectfill\n%%EOF\n";
|
||||
let nested = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n%%BeginDocument: c.eps\nnewpath\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n";
|
||||
let place = |path: &str, matrix: &str, doc: &str| {
|
||||
format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n{matrix} 0 0 60 40 4 4 0\n({path})`\n%%BeginDocument: {path}\n{doc}\n%%EndDocument\n\
|
||||
%AI17_Begin_Content_if_version_gt:24 12\n%AI28_BeginPlacedRelativePath\n(src/)\n%AI28_EndPlacedRelativePath\n%AI17_Alternate_Content\n%AI17_End_Versioned_Content\n~\n%AI5_EndPlace\n"
|
||||
)
|
||||
};
|
||||
let hidden: String = place("/tmp/b.eps", "[1 0 0 1 20 20]", eps).lines().map(|l| format!("%_{l}\n")).collect();
|
||||
let body = format!("{}{hidden}{}", place("/tmp/a.eps", "[1 0 0 1 20 20]", eps), place("/tmp/c.eps", "[1 0 0 1 0 0]", nested));
|
||||
let fixture = ai::editing_data(200.0, 100.0, &ai::layer("L", &body));
|
||||
// A session reads placed documents' files when they are drawn.
|
||||
let _ = vectorcraft_engine::Session::new();
|
||||
let whole = vectorcraft_engine::cmd::fileio::load("x.ai", &ai::ai(fixture.as_bytes(), "0 0 1 rg 20 20 60 40 re f"));
|
||||
let mut placed = 0;
|
||||
whole.iter().for_each(|l| l.doc.visit_placed(|_, _| placed += 1));
|
||||
prop_assert!(placed == 3 && fixture.len() < 4_000, "{placed} placed documents, {} bytes: {:?}", fixture.len(), whole.map(|l| l.warnings));
|
||||
let text = mutate_text(&fixture, cut, &edits);
|
||||
let file = ai::ai(text.as_bytes(), "0 0 1 rg 20 20 60 40 re f");
|
||||
survive("hostile .ai placed EPS files with included bytes", || vectorcraft_engine::cmd::fileio::load("x.ai", &file).ok().map(|l| l.doc))?;
|
||||
}
|
||||
|
||||
/// A `.ai` whose type (point type turned, vertical type, area type, threaded area type and type
|
||||
/// on a path, their stubs with the frames' paths, and the text document they name, as the `.ai`
|
||||
/// writer writes them) is damaged: read from its editing data alone and beside a page.
|
||||
@@ -6390,6 +6421,12 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
|
||||
"\n%%BeginData: 14 Binary Bytes\n",
|
||||
"\n%%BeginBinary: 99999999999\n",
|
||||
"\n%%BeginData: 3 Hex Lines\n",
|
||||
// A placed EPS file's bytes included in the data: one drawn, one with a box it can't
|
||||
// take, one on `%_` lines.
|
||||
"\n%%BeginDocument: a.eps\n%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 9 9\n0 0 1 setrgbcolor 0 0 9 9 rectfill\n%%EndDocument\n",
|
||||
"\n%%BeginDocument: a.eps\n%!PS\n%%BoundingBox: 0 0 1e308 -5\n%%EndDocument\n",
|
||||
"\n%_%%BeginDocument: a.eps\n%_%!PS\n%_0 0 9 9 rectfill\n%_%%EndDocument\n",
|
||||
"[1 0 0 1 0 0] 0 0 1e308 1e308 4 4 0 (a.eps) `",
|
||||
"\n%AI5_EndPlace\n",
|
||||
"Xm",
|
||||
"50 -50 -100 -100 5000 -2000 Xm",
|
||||
|
||||
@@ -9,7 +9,8 @@ description = "VectorCraft Encapsulated PostScript: a hand-written EPS writer (P
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# `vectorcraft_eps::blend_work` for other crates' tests (dev-dependencies only).
|
||||
# `vectorcraft_eps::blend_work` and `vectorcraft_eps::included_eps_reads` for other crates' tests
|
||||
# (dev-dependencies only).
|
||||
work-count = []
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -280,6 +280,12 @@ pub fn page(bytes: &[u8]) -> Result<Rect, String> {
|
||||
Ok(Rect::new(0.0, 0.0, urx - llx, ury - lly))
|
||||
}
|
||||
|
||||
/// An EPS or PostScript file's bounding box (`%%HiResBoundingBox` when it has one) in its own
|
||||
/// space, as `[llx, lly, urx, ury]`, read from its comments; `None` without one.
|
||||
pub(crate) fn bounding_box(bytes: &[u8]) -> Option<[f64; 4]> {
|
||||
Dsc::read(program(bytes).ok()?).bbox
|
||||
}
|
||||
|
||||
/// [`import`], an Illustrator EPS through the editing copy of its art only when `editing_data`
|
||||
/// (else what its page prints, as any EPS).
|
||||
pub fn import_with(bytes: &[u8], editing_data: bool) -> Result<Imported, String> {
|
||||
|
||||
@@ -62,12 +62,12 @@ pub use read::read;
|
||||
#[cfg(test)]
|
||||
pub(crate) use read::with_image_limits;
|
||||
pub(crate) use read::{
|
||||
BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, parsed_type_color,
|
||||
read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
BLEND_BUDGET, LINKED_PREVIEWS, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with,
|
||||
parsed_type_color, read_over_page, read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member,
|
||||
};
|
||||
pub use read::{
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles,
|
||||
palette, read_beside, read_in, symbols, variables,
|
||||
BindingRef, Brushes, PaletteSwatches, PlacedEps, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes,
|
||||
graphic_styles, palette, read_beside, read_in, symbols, variables,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(crate) use style::ART_STYLE_PARSES;
|
||||
|
||||
@@ -57,8 +57,13 @@
|
||||
//! The version 7 form (§16) has no `%AI5_BeginPlace`: `[matrix] llx lly urx ury (path)` and
|
||||
//! `` ` ``, then `%%IncludeFile:` or the file between `%%BeginDocument:` and `%%EndDocument`,
|
||||
//! then `~`; its box is the file's `%%BoundingBox`. Newer files have three more numbers before
|
||||
//! the path. Operands of any other shape, a second `` ` `` before `~` or an included document
|
||||
//! that doesn't end leave the placed file unread.
|
||||
//! the path. A placed EPS file whose bytes are included between `%%BeginDocument:` and
|
||||
//! `%%EndDocument` (DSC 3.0 p. 68) is a placed document that keeps those bytes and draws them,
|
||||
//! its file found or not; its box is the
|
||||
//! file's bounding box, which the matrix takes from the file's own space (y up) into art space,
|
||||
//! as in the version 7 form.
|
||||
//! Operands of any other shape, a second `` ` `` before `~` or an included document that
|
||||
//! doesn't end leave the placed file unread.
|
||||
//! - Art with an appearance the format can't write as plain art (several fills or strokes,
|
||||
//! effects, brushes) comes first as that look, drawn (a group, or an image where an effect
|
||||
//! rasterizes it), then the object itself on `%_`
|
||||
@@ -148,7 +153,7 @@ mod raster;
|
||||
mod types;
|
||||
|
||||
pub(crate) use art::join_and;
|
||||
use art::preview_png;
|
||||
use art::{included_document, preview_png};
|
||||
pub use document::{
|
||||
BindingRef, Brushes, PaletteSwatches, Symbols, VariableRead, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette,
|
||||
symbols, variables,
|
||||
@@ -163,11 +168,12 @@ pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, parsed_typ
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::with_image_limits;
|
||||
pub(crate) use types::BLEND_BUDGET;
|
||||
pub(crate) use types::LINKED_PREVIEWS;
|
||||
pub(crate) use types::MAX_NODES;
|
||||
pub use types::PlacedPage;
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
use types::{BrushArtColors, FLIP, Frame, GState, Kind, MAX_PLACED_DOCUMENT, PatternHead, PendingEnvelope, Place, PlacedTail, Raster, SymbolHead};
|
||||
#[cfg(test)]
|
||||
pub use types::{GRAPH_PLAIN, GRAPH_UNENDED, LINKED_PLACEHOLDERS, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, VERSIONED_UNENDED};
|
||||
pub use types::{PlacedEps, PlacedPage};
|
||||
pub(super) use types::{blend_mode, blend_name};
|
||||
|
||||
#[path = "legacy_text.rs"]
|
||||
@@ -216,6 +222,8 @@ pub struct Structure {
|
||||
pub placed_elsewhere: Vec<(NodeId, Affine)>,
|
||||
/// The placed files that are pages of PDF or `.ai` files.
|
||||
pub placed_pages: Vec<PlacedPage>,
|
||||
/// Included EPS files whose previews wait for variable binding before conversion.
|
||||
pub placed_eps: Vec<PlacedEps>,
|
||||
/// The live envelopes read from the editing data, by id, with the drawn art each took the place
|
||||
/// of: the importer puts that art back when the layers with the envelopes don't draw as the page.
|
||||
pub envelopes_drawn: Vec<(NodeId, Node)>,
|
||||
@@ -677,6 +685,8 @@ struct Reader<'a> {
|
||||
placed_elsewhere: Vec<(NodeId, Affine)>,
|
||||
/// See [`Structure::placed_pages`].
|
||||
placed_pages: Vec<PlacedPage>,
|
||||
/// See [`Structure::placed_eps`].
|
||||
placed_eps: Vec<PlacedEps>,
|
||||
unread_elsewhere: Vec<(NodeId, Rect)>,
|
||||
/// CMYK samples converted, by value.
|
||||
cmyk_cache: HashMap<[u8; 4], [u8; 3]>,
|
||||
@@ -912,6 +922,7 @@ impl<'a> Reader<'a> {
|
||||
placeholders: vec![],
|
||||
placed_elsewhere: vec![],
|
||||
placed_pages: vec![],
|
||||
placed_eps: vec![],
|
||||
placed_tails: vec![],
|
||||
unread_elsewhere: vec![],
|
||||
mesh: None,
|
||||
@@ -950,6 +961,15 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The line end just before `doc`, an included document the lexer has just read: the one that
|
||||
/// ends its `%%BeginDocument:` line. `None` when `doc` isn't in the data read so far.
|
||||
fn line_end_before(&self, doc: &[u8]) -> Option<&'static [u8]> {
|
||||
let read = self.lex.slice(0, self.lex.offset());
|
||||
let at = doc.as_ptr().addr().checked_sub(read.as_ptr().addr())?;
|
||||
let before = read.get(..at)?;
|
||||
[&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| before.ends_with(e))
|
||||
}
|
||||
|
||||
fn run(&mut self) -> Result<(), String> {
|
||||
while let Some(t) = self.lex.next_token() {
|
||||
if self.done {
|
||||
@@ -972,11 +992,14 @@ impl<'a> Reader<'a> {
|
||||
p.preview = preview_png(d);
|
||||
}
|
||||
}
|
||||
// A placed file's document, included whole: its art isn't read here. When no
|
||||
// `%%EndDocument` ends it, the placed file isn't read.
|
||||
// A placed file's document, included whole: its art isn't read here, its bytes are
|
||||
// kept for the placed file. When no `%%EndDocument` ends it, the placed file isn't
|
||||
// read.
|
||||
Tok::Document(d) => {
|
||||
let sep = d.and_then(|d| self.line_end_before(d));
|
||||
if let Some(p) = self.place.as_mut() {
|
||||
p.broken |= d.is_none();
|
||||
p.document = d.filter(|d| d.len() <= MAX_PLACED_DOCUMENT).map(|d| included_document(d, hidden, sep));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,88 @@ use super::containers::close;
|
||||
use super::document::TEXT_SLOT;
|
||||
use super::raster::{self, Limits, Shape};
|
||||
use super::types::{
|
||||
FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE, MAX_POINTS,
|
||||
MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedPage, PlacedTail,
|
||||
EPS_MIME, FLIP, Frame, GState, IMAGE_TOO_LARGE, Kind, LARGE_IMAGES, LINKED_PLACEHOLDERS, LINKED_PREVIEWS, MAX_PIXELS, MAX_PLACED_ELSEWHERE,
|
||||
MAX_POINTS, MAX_SIDE, NON_NATIVE_ART, NON_NATIVE_ART_UNREAD, PLACED_CROP, PLACED_PAGE, Place, PlacedEps, PlacedPage, PlacedTail,
|
||||
};
|
||||
use super::{
|
||||
Affine, AnchorKind, Appearance, AppearanceItem, Arc, BezPath, CANVAS_CENTRE, FillLayer, ImageBlob, ImageObject, Inks, Instance, LinkInfo, Node,
|
||||
NodeId, NodeKind, Obj, OpacityMask, PageBox, Paint, PathData, PathEl, Point, Reader, Rect, StrokeLayer, V, ps,
|
||||
};
|
||||
use vectorcraft_doc::links::missing_placeholder;
|
||||
use vectorcraft_doc::PlacedDocument;
|
||||
use vectorcraft_doc::links::{hash_bytes, missing_placeholder};
|
||||
use vectorcraft_doc::placed_document::key_for;
|
||||
use vectorcraft_pdf::is_postscript;
|
||||
|
||||
/// Open-check results by content and nesting depth: the remaining depth changes their warnings.
|
||||
type EpsChecks = Vec<((String, usize), Option<Vec<String>>)>;
|
||||
|
||||
/// The most open-check results kept during one outer check; no file bytes are retained.
|
||||
const MAX_EPS_CHECKS: usize = 64;
|
||||
|
||||
std::thread_local! {
|
||||
/// How many included EPS files [`readable_eps`] is reading inside one another on this thread.
|
||||
static READING_EPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
/// Checks completed during this thread's outer check, including files that do not read.
|
||||
static EPS_CHECKS: std::cell::RefCell<EpsChecks> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
/// An included EPS file being read by [`readable_eps`] ([`READING_EPS`]): the count goes down when
|
||||
/// this goes.
|
||||
struct ReadingEps;
|
||||
|
||||
impl ReadingEps {
|
||||
/// `None` when 8 are being read.
|
||||
fn enter() -> Option<Self> {
|
||||
READING_EPS.with(|d| (d.get() < 8).then(|| d.set(d.get() + 1))).map(|()| Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ReadingEps {
|
||||
fn drop(&mut self) {
|
||||
READING_EPS.with(|d| d.set(d.get().saturating_sub(1)));
|
||||
if READING_EPS.with(std::cell::Cell::get) == 0 {
|
||||
EPS_CHECKS.with_borrow_mut(Vec::clear);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The warnings of reading `bytes` as an EPS file, the way a placed document's art is read from
|
||||
/// them (art left out after an operator that isn't read, for one); `None` when they don't read.
|
||||
/// Past 8 included files read inside one another they count as readable without warnings; drawing
|
||||
/// reads a bounded number of them in turn. The check uses previews for placed documents, so
|
||||
/// drawing does not start another chain of checks inside this one. Repeated structural reads
|
||||
/// share completed checks at the same depth until the outer check ends.
|
||||
fn readable_eps(bytes: &[u8]) -> Option<Vec<String>> {
|
||||
let key = (hash_bytes(bytes), READING_EPS.with(std::cell::Cell::get));
|
||||
if let Some(warnings) = EPS_CHECKS.with_borrow(|c| c.iter().find(|(k, _)| *k == key).map(|(_, warnings)| warnings.clone())) {
|
||||
return warnings;
|
||||
}
|
||||
let Some(_reading) = ReadingEps::enter() else { return Some(vec![]) };
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
crate::INCLUDED_EPS_READS.with(|n| n.set(n.get() + 1));
|
||||
let warnings = vectorcraft_doc::placed_document::with_previews(|| {
|
||||
crate::import_names(bytes, true, false, crate::NameEncoding::default()).ok().map(|r| r.warnings)
|
||||
});
|
||||
EPS_CHECKS.with_borrow_mut(|c| {
|
||||
if c.len() >= MAX_EPS_CHECKS {
|
||||
c.remove(0);
|
||||
}
|
||||
c.push((key, warnings.clone()));
|
||||
});
|
||||
warnings
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
/// Do the bytes `eps` of an included EPS file read ([`readable_eps`])? When they do, what reading
|
||||
/// them warns of is a warning of this file's too.
|
||||
fn read_included(&mut self, eps: &[u8]) -> bool {
|
||||
let Some(warnings) = readable_eps(eps) else { return false };
|
||||
for w in warnings {
|
||||
self.warn(&format!("a placed EPS file: {w}"));
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// A text object (`/AI11Text`): an empty group standing for it, named after its story.
|
||||
pub(super) fn text_slot(&mut self, o: &Obj) -> Result<(), String> {
|
||||
if self.pattern.is_some() {
|
||||
@@ -838,8 +909,9 @@ impl<'a> Reader<'a> {
|
||||
}
|
||||
|
||||
/// `~`: the placed file read since `%AI5_BeginPlace` becomes a linked image in its place that
|
||||
/// shows the preview the data keeps of it, as a linked image whose file is missing does. One
|
||||
/// without a preview, a path or a matrix isn't read.
|
||||
/// shows the preview the data keeps of it, as a linked image whose file is missing does. An EPS
|
||||
/// file whose bytes the data includes becomes a placed document of them ([`Self::placed_eps`]).
|
||||
/// One without a preview or those bytes, a path or a matrix isn't read.
|
||||
pub(super) fn end_place(&mut self, hidden: bool) -> Result<(), String> {
|
||||
// Where a symbol's art puts a placed file's pixels isn't known.
|
||||
if self.symbol.is_some() {
|
||||
@@ -847,11 +919,43 @@ impl<'a> Reader<'a> {
|
||||
self.left_out_of_symbol();
|
||||
return Ok(());
|
||||
}
|
||||
let mut deferred = None;
|
||||
let (m, b, path, png, w, h, folder) = match self.place.take() {
|
||||
Some(Place { broken: true, .. }) => {
|
||||
self.unreadable("placed files", hidden);
|
||||
return Ok(());
|
||||
}
|
||||
Some(Place { matrix: Some(m), bounds: Some(b), path, document: Some(eps), preview, folder, .. })
|
||||
// A file without a bounding box of its own has its art read on a page of another
|
||||
// size, which the placed box can't be matched to.
|
||||
// One named `.ai` or `.ait` is read with the artboard its header gives rather than
|
||||
// its bounding box, so it isn't read either. Bytes that don't read as an EPS file
|
||||
// leave it as a placed file without them: its preview, or an unread one.
|
||||
if !path.is_empty()
|
||||
&& !ai_named(&path)
|
||||
&& is_postscript(&eps)
|
||||
// A native document's artboard, rather than its bounding box, frames what the loader reads.
|
||||
&& !native_eps(&eps)
|
||||
&& crate::dcs::read(&eps).is_none()
|
||||
&& sane(b)
|
||||
&& b.width() > 0.0
|
||||
&& b.height() > 0.0
|
||||
&& eps_box(&eps).is_some()
|
||||
&& self.read_included(&eps) =>
|
||||
{
|
||||
let Some((placed, blob)) = self.placed_eps(m, path.clone(), eps, folder.clone(), hidden) else { return Ok(()) };
|
||||
if let Some((png, w, h)) = preview {
|
||||
// No image variable binds pattern or brush art, which a reader of its own
|
||||
// reads: there the placed document goes in at once.
|
||||
if self.pattern.is_some() {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
deferred = Some((placed, blob));
|
||||
(m, b, path, png, w, h, folder)
|
||||
} else {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
}
|
||||
Some(Place { matrix: Some(m), bounds: Some(b), path, preview: Some((png, w, h)), folder, .. }) if !path.is_empty() => {
|
||||
(m, b, path, png, w, h, folder)
|
||||
}
|
||||
@@ -902,6 +1006,10 @@ impl<'a> Reader<'a> {
|
||||
.filter(|a| a.as_coeffs().iter().all(|v| v.is_finite()));
|
||||
let xf = self.space() * m * over_file;
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
// An included EPS file is still read when its preview can't be placed.
|
||||
if let Some((placed, blob)) = deferred {
|
||||
return self.add_placed_eps(placed, blob, hidden);
|
||||
}
|
||||
self.unreadable("placed files", hidden);
|
||||
return Ok(());
|
||||
}
|
||||
@@ -911,7 +1019,11 @@ impl<'a> Reader<'a> {
|
||||
let key = linked_key(&blob, &path);
|
||||
let fresh = !self.doc.images.contains_key(&key);
|
||||
self.doc.images.entry(key.clone()).or_insert(blob);
|
||||
self.warn(LINKED_PREVIEWS);
|
||||
// An included EPS file shows its preview only when an image variable binds it, which the
|
||||
// importer notes then.
|
||||
if deferred.is_none() {
|
||||
self.warn(LINKED_PREVIEWS);
|
||||
}
|
||||
let id = NodeId(self.doc.peek_next_id());
|
||||
if let Some(shift) = elsewhere
|
||||
&& self.placed_elsewhere.len() < MAX_PLACED_ELSEWHERE
|
||||
@@ -928,7 +1040,11 @@ impl<'a> Reader<'a> {
|
||||
self.placed_tails.push(PlacedTail { id, key: key.clone(), size: (b.width(), b.height()), fresh, depth });
|
||||
let mut link = LinkInfo::new(path);
|
||||
link.relative = folder.and_then(|f| relative_path(&f, link.name()));
|
||||
self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)
|
||||
self.add_image(ImageObject { key, width: w, height: h, xf, link: Some(link), placement: Default::default(), pixels: None }, hidden)?;
|
||||
if let Some((placed, blob)) = deferred {
|
||||
self.placed_eps.push(PlacedEps { id, placed, blob });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The dictionary `o` after the placed file just read: with a page or a box in it, that file is
|
||||
@@ -962,6 +1078,54 @@ impl<'a> Reader<'a> {
|
||||
self.placed_pages.push(PlacedPage { id: tail.id, page, bounding, page_box, size: tail.size });
|
||||
}
|
||||
|
||||
/// The placed EPS file at `path` whose bytes `eps` the data includes, its box (in its own space,
|
||||
/// y up: the bounding box its comments give, [`eps_box`], which its art is read in) taken into
|
||||
/// art space by `m`: a placed document showing that box, which keeps the bytes and draws them
|
||||
/// whether or not its file is found. Its link has the size and hash of those bytes, so a file
|
||||
/// found unchanged isn't reported as modified. The placed document has no preview, so a save
|
||||
/// keeps the bytes. Not read without that box.
|
||||
fn placed_eps(&mut self, m: Affine, path: String, eps: Vec<u8>, folder: Option<String>, hidden: bool) -> Option<(PlacedDocument, ImageBlob)> {
|
||||
let Some(b) = eps_box(&eps) else {
|
||||
self.unreadable("placed files", hidden);
|
||||
return None;
|
||||
};
|
||||
// The placed document's box runs down from the file's top left corner.
|
||||
let xf = self.space() * m * Affine::new([1.0, 0.0, 0.0, -1.0, b.x0, b.y1]);
|
||||
if !xf.as_coeffs().iter().all(|v| v.is_finite()) || xf.determinant().abs() < 1e-12 {
|
||||
self.unreadable("placed files", hidden);
|
||||
return None;
|
||||
}
|
||||
let hash = hash_bytes(&eps);
|
||||
let key = key_for(&hash, 1, false, PageBox::Crop);
|
||||
let mut link = LinkInfo::new(path);
|
||||
link.relative = folder.and_then(|f| relative_path(&f, link.name()));
|
||||
(link.page, link.size, link.hash) = (Some(1), u64::try_from(eps.len()).ok(), Some(hash));
|
||||
let blob = ImageBlob { mime: EPS_MIME.into(), bytes: Arc::new(eps), proxy: None, file_font: Default::default() };
|
||||
let placed = PlacedDocument {
|
||||
link,
|
||||
key,
|
||||
bounding: false,
|
||||
page_box: PageBox::Crop,
|
||||
width: b.width(),
|
||||
height: b.height(),
|
||||
xf,
|
||||
placement: Default::default(),
|
||||
};
|
||||
Some((placed, blob))
|
||||
}
|
||||
|
||||
/// `placed` ([`Self::placed_eps`]) added as an object, its bytes `blob` kept under its key.
|
||||
/// Placements of the same bytes share one blob.
|
||||
fn add_placed_eps(&mut self, placed: PlacedDocument, blob: ImageBlob, hidden: bool) -> Result<(), String> {
|
||||
self.doc.images.entry(placed.key.clone()).or_insert(blob);
|
||||
let gs = self.gs.clone();
|
||||
let mut node = self.new_node(NodeKind::PlacedDocument(Box::new(placed)), &gs);
|
||||
node.opacity = gs.opacity;
|
||||
node.blend = gs.blend;
|
||||
node.knockout_shape = gs.knockout_shape;
|
||||
self.add(node, hidden)
|
||||
}
|
||||
|
||||
pub(super) fn warn(&mut self, w: &str) {
|
||||
if !self.warnings.iter().any(|x| x == w) && self.warnings.len() < 64 {
|
||||
self.warnings.push(w.to_string());
|
||||
@@ -1083,6 +1247,65 @@ fn placed_crop(v: f64) -> Option<(bool, PageBox)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of a placed file the data includes (`doc`: between the `%%BeginDocument:` line and
|
||||
/// the `%%EndDocument` one), as the file has them: on `%_` lines (`hidden`) without the `%_` that
|
||||
/// starts each line, then without a line end the data adds before `%%EndDocument` after the file's
|
||||
/// own last one. A single line end at the end is the file's own. The line end added is `sep`, the
|
||||
/// one the data ends its `%%BeginDocument:` line with, when the bytes end with it; otherwise the
|
||||
/// last line end they end with. An LF `sep` after a CR isn't taken apart from it when the file's
|
||||
/// first line ends with CRLF: that CRLF is one line end of the file's.
|
||||
pub(super) fn included_document(doc: &[u8], hidden: bool, sep: Option<&[u8]>) -> Vec<u8> {
|
||||
let mut out = if hidden { unhidden(doc) } else { doc.to_vec() };
|
||||
let eol = |b: &[u8]| b.ends_with(b"\r") || b.ends_with(b"\n");
|
||||
let first_eol = out.iter().position(|&b| b == b'\r' || b == b'\n').and_then(|i| out.get(i..i + 2));
|
||||
let crlf_file = first_eol == Some(b"\r\n") && out.ends_with(b"\r\n");
|
||||
let added = sep
|
||||
.filter(|s| out.ends_with(s) && !(crlf_file && *s == b"\n"))
|
||||
.or_else(|| [&b"\r\n"[..], b"\r", b"\n"].into_iter().find(|e| out.ends_with(e)))
|
||||
.map(|e| out.len() - e.len());
|
||||
if let Some(n) = added.filter(|&n| out.get(..n).is_some_and(eol)) {
|
||||
out.truncate(n);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The bounding box an EPS file's comments give (`%%HiResBoundingBox` when it has one), in its
|
||||
/// own space; `None` without one, or when it is empty or out of range.
|
||||
fn eps_box(eps: &[u8]) -> Option<Rect> {
|
||||
let [x0, y0, x1, y1] = crate::import::bounding_box(eps)?;
|
||||
Some(Rect::new(x0, y0, x1, y1)).filter(|r| sane(*r) && r.width() > 0.0 && r.height() > 0.0)
|
||||
}
|
||||
|
||||
/// Does `eps` have a native document's begin comment line, without reading that document?
|
||||
fn native_eps(eps: &[u8]) -> bool {
|
||||
eps.split(|b| *b == b'\r' || *b == b'\n')
|
||||
.any(|line| line.strip_prefix(crate::BEGIN_DATA.as_bytes()).is_some_and(|name| name.trim_ascii() == crate::NATIVE.as_bytes()))
|
||||
}
|
||||
|
||||
/// Does the file name at the end of `path` (`/` or `\` separators) end in `.ai` or `.ait`, any case?
|
||||
fn ai_named(path: &str) -> bool {
|
||||
let name = path.rsplit(['/', '\\']).next().unwrap_or(path);
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("ai") || ext.eq_ignore_ascii_case("ait"))
|
||||
}
|
||||
|
||||
/// `doc` without the `%_` that starts each of its lines.
|
||||
fn unhidden(doc: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(doc.len());
|
||||
let mut line_start = true;
|
||||
let mut i = 0;
|
||||
while let Some(&b) = doc.get(i) {
|
||||
if line_start && doc.get(i..i + 2) == Some(b"%_") {
|
||||
i += 2;
|
||||
line_start = false;
|
||||
continue;
|
||||
}
|
||||
out.push(b);
|
||||
line_start = b == b'\r' || b == b'\n';
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A placed file's path relative to the document's folder (`/` separators): its relative `folder`
|
||||
/// (`src/`, `..\art`) followed by its file `name`; the name alone when the folder is empty (the
|
||||
/// document's own folder). `None` when the folder is absolute or holds control characters, or
|
||||
@@ -1155,3 +1378,36 @@ pub(crate) fn join_and(items: &[&str]) -> String {
|
||||
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ReadingEps, readable_eps};
|
||||
|
||||
/// Check results keep their warnings and failures, respect depth, and expire with the outer check.
|
||||
#[test]
|
||||
fn included_eps_checks_keep_the_depth_limit_and_expire() {
|
||||
let eps = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n1 0 0 setrgbcolor 0 0 60 60 rectfill nosuchoperator\n%%EOF\n";
|
||||
{
|
||||
let _outer = ReadingEps::enter().unwrap();
|
||||
let warnings = readable_eps(eps).unwrap();
|
||||
assert!(!warnings.is_empty(), "a partly read file still passes, with warnings");
|
||||
let reads = crate::included_eps_reads();
|
||||
assert_eq!(readable_eps(eps).unwrap(), warnings);
|
||||
assert_eq!(crate::included_eps_reads(), reads, "the repeated check did not parse again");
|
||||
let limits: Vec<_> = std::iter::from_fn(ReadingEps::enter).collect();
|
||||
assert!(!limits.is_empty());
|
||||
assert!(readable_eps(eps).unwrap().is_empty(), "past the depth limit, warnings are not read");
|
||||
drop(limits);
|
||||
assert_eq!(readable_eps(eps).unwrap(), warnings, "the deeper check did not replace the cached warnings");
|
||||
let broken = b"%!PS\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
assert!(readable_eps(broken).is_none());
|
||||
let reads = crate::included_eps_reads();
|
||||
assert!(readable_eps(broken).is_none());
|
||||
assert_eq!(crate::included_eps_reads(), reads, "a repeated failed check did not parse again");
|
||||
}
|
||||
let _outer = ReadingEps::enter().unwrap();
|
||||
let reads = crate::included_eps_reads();
|
||||
assert!(readable_eps(eps).is_some());
|
||||
assert!(crate::included_eps_reads() > reads, "the outer check's results were discarded");
|
||||
}
|
||||
}
|
||||
@@ -1468,6 +1468,7 @@ impl<'a> Reader<'a> {
|
||||
placeholders: self.placeholders,
|
||||
placed_elsewhere: self.placed_elsewhere,
|
||||
placed_pages: self.placed_pages,
|
||||
placed_eps: self.placed_eps,
|
||||
envelopes_drawn: self.envelopes_drawn,
|
||||
warped_type: super::super::envelope::WarpedType {
|
||||
looks: self.warped_type,
|
||||
|
||||
@@ -312,6 +312,9 @@ pub(super) struct Place {
|
||||
pub(super) folder: Option<String>,
|
||||
/// The operand stack's height at `%AI28_BeginPlacedRelativePath`, until its end.
|
||||
pub(super) folder_at: Option<usize>,
|
||||
/// The file's bytes, when the data includes them between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` (at most [`MAX_PLACED_DOCUMENT`]).
|
||||
pub(super) document: Option<Vec<u8>>,
|
||||
/// Its `` ` `` was read.
|
||||
pub(super) ticked: bool,
|
||||
/// It began on a `%_` line, in a hidden object or on a layer that doesn't show.
|
||||
@@ -361,8 +364,26 @@ pub struct PlacedPage {
|
||||
pub size: (f64, f64),
|
||||
}
|
||||
|
||||
/// An included EPS whose linked preview becomes a placed document after variable binding.
|
||||
#[derive(Debug)]
|
||||
pub struct PlacedEps {
|
||||
/// The linked image.
|
||||
pub id: NodeId,
|
||||
/// The document that replaces the image unless an image variable binds it.
|
||||
pub placed: vectorcraft_doc::PlacedDocument,
|
||||
/// The EPS bytes stored under the placed document's key only when it replaces the image.
|
||||
pub blob: vectorcraft_doc::ImageBlob,
|
||||
}
|
||||
|
||||
/// The largest placed file kept from the bytes the data includes (the largest file File › Place
|
||||
/// reads).
|
||||
pub(super) const MAX_PLACED_DOCUMENT: usize = 256 << 20;
|
||||
|
||||
/// The type a placed EPS file's bytes are stored with.
|
||||
pub(super) const EPS_MIME: &str = "application/postscript";
|
||||
|
||||
/// What the open result says of placed files: they show the preview the file keeps of them.
|
||||
pub(super) const LINKED_PREVIEWS: &str =
|
||||
pub(crate) const LINKED_PREVIEWS: &str =
|
||||
"linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel";
|
||||
|
||||
/// What the open result says of linked images the data keeps no pixels of (`XF`): they show a
|
||||
|
||||
@@ -12,7 +12,9 @@ use super::*;
|
||||
|
||||
/// [`super::read`] as an EPS reads it.
|
||||
fn read(data: &[u8]) -> Result<Structure, String> {
|
||||
super::read(data, true)
|
||||
let mut r = super::read(data, true)?;
|
||||
super::super::native::placed_documents(&mut r.doc, &[], &r.placed_eps);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// Editing data: header comments (crop marks 0 0 200 100), then `body`.
|
||||
@@ -3495,6 +3497,178 @@ fn a_placed_file_keeps_its_folder_relative_to_the_document() {
|
||||
assert_eq!(relative_of(&cut), None);
|
||||
}
|
||||
|
||||
/// An EPS file of `w` × `h` points filled red, its lines ended by `eol`.
|
||||
fn red_eps(w: u32, h: u32, eol: &str) -> Vec<u8> {
|
||||
format!("%!PS-Adobe-3.0 EPSF-3.0{eol}%%BoundingBox: 0 0 {w} {h}{eol}%%EndComments{eol}1 0 0 setrgbcolor{eol}0 0 {w} {h} rectfill{eol}%%EOF{eol}")
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
/// `data` with the first `from` in it replaced by `to`.
|
||||
fn splice(data: &[u8], from: &[u8], to: &[u8]) -> Vec<u8> {
|
||||
let at = data.windows(from.len()).position(|w| w == from).unwrap();
|
||||
[&data[..at], to, &data[at + from.len()..]].concat()
|
||||
}
|
||||
|
||||
/// [`placed`]'s file with the placed file `/old/place/src/shape.eps` in the box 0 0 80 50, in the
|
||||
/// folder `src/`, without a preview, and `doc` included between `%%BeginDocument:` and
|
||||
/// `%%EndDocument` in place of `%%IncludeFile:` (`%%FileType: 0`).
|
||||
fn placed_eps_file(doc: &[u8]) -> Vec<u8> {
|
||||
let data = placed(true, "[5 0 0 -5 0 200]", "/old/place/src/shape.eps", None, "");
|
||||
let data = splice(&data, b"10 20 14 22 4 4 0", b"0 0 80 50 4 4 0");
|
||||
let data = splice(&data, b"\r()\r", b"\r(src/)\r");
|
||||
let data = splice(&data, b"%%FileType: 1", b"%%FileType: 0");
|
||||
let included = [&b"%%BeginDocument: /old/place/src/shape.eps\r"[..], doc, b"\r%%EndDocument\r"].concat();
|
||||
splice(&data, b"%%IncludeFile:/old/place/src/shape.eps\r", &included)
|
||||
}
|
||||
|
||||
/// The one placed document of `data`, with the blob its key names.
|
||||
fn one_placed(data: &[u8]) -> (Node, vectorcraft_doc::PlacedDocument, vectorcraft_doc::ImageBlob, Structure) {
|
||||
let r = read(data).unwrap();
|
||||
let a = art(&r.doc);
|
||||
let [n] = &a[..] else { panic!("one object: {a:?}") };
|
||||
let NodeKind::PlacedDocument(p) = &n.kind else { panic!("a placed document: {:?}", n.kind) };
|
||||
let blob = r.doc.images[&p.key].clone();
|
||||
((**n).clone(), (**p).clone(), blob, r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_whose_bytes_the_data_includes_is_a_placed_document_of_them() {
|
||||
let eps = red_eps(80, 50, "\n");
|
||||
let (_, p, blob, r) = one_placed(&placed_eps_file(&eps));
|
||||
assert_eq!(*blob.bytes, eps, "the file's own bytes, without the line end the data adds");
|
||||
assert_eq!((blob.mime.as_str(), blob.proxy.is_none()), ("application/postscript", true));
|
||||
assert_eq!((p.link.path.as_str(), p.link.relative.as_deref()), ("/old/place/src/shape.eps", Some("src/shape.eps")));
|
||||
assert_eq!((p.link.page, p.link.size, p.link.hash.clone()), (Some(1), Some(eps.len() as u64), Some(vectorcraft_doc::links::hash_bytes(&eps))));
|
||||
assert_eq!((p.width, p.height, p.bounding, p.page_box), (80.0, 50.0, false, vectorcraft_doc::PageBox::Crop));
|
||||
assert!(r.unread.is_empty() && r.hidden_unread.is_empty() && r.unread_elsewhere.is_empty(), "{:?}", r.unread);
|
||||
assert!(!r.warnings.iter().any(|w| w == read::LINKED_PLACEHOLDERS), "{:?}", r.warnings);
|
||||
// The matrix takes the file's own space (y up) into art space; the box's top left corner is the
|
||||
// file's (0, 50).
|
||||
let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]);
|
||||
for (corner, file) in [((0.0, 0.0), (0.0, 50.0)), ((80.0, 50.0), (80.0, 0.0)), ((80.0, 0.0), (80.0, 50.0))] {
|
||||
let (got, want) = (p.xf * Point::from(corner), r.to_doc * m * Point::from(file));
|
||||
assert!((got - want).hypot() < 1e-9, "{corner:?}: {got:?} {want:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_with_included_bytes_and_a_preview_keeps_only_the_bytes() {
|
||||
let eps = red_eps(80, 50, "\n");
|
||||
let preview = [&b"2 1 12 32 17 "[..], &[255, 255, 0, 0, 128, 0, 64, 0, 9, 9, 9, 9]].concat();
|
||||
let section =
|
||||
[&b"%AI17_Begin_Content_if_version_gt:24 5\r%AI26_BeginPlacedObjectPreview\r"[..], &preview, b"\r%AI26_EndPlacedObjectPreview\r"].concat();
|
||||
let data = splice(&placed_eps_file(&eps), b"%AI17_Begin_Content_if_version_gt:24 5\r", §ion);
|
||||
// The placed document has no preview, so a save keeps its bytes.
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!((&*blob.bytes, blob.proxy.is_none()), (&eps, true));
|
||||
// The same bytes placed twice share the blob.
|
||||
let one = placed_eps_file(&eps);
|
||||
let (from, to) = (|d: &[u8], w: &[u8]| d.windows(w.len()).position(|x| x == w).unwrap(), b"%AI5_EndPlace\r");
|
||||
let first = &one[from(&one, b"%AI5_BeginPlace")..from(&one, to) + to.len()];
|
||||
let twice = splice(&data, b"%AI5_BeginPlace", &[first, b"%AI5_BeginPlace"].concat());
|
||||
let r = read(&twice).unwrap();
|
||||
let a = art(&r.doc);
|
||||
let keys: Vec<_> = a.iter().filter_map(|n| if let NodeKind::PlacedDocument(p) = &n.kind { Some(p.key.clone()) } else { None }).collect();
|
||||
assert!(keys.len() == 2 && keys[0] == keys[1], "{keys:?}");
|
||||
assert!(r.doc.images[&keys[0]].proxy.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_files_box_is_its_high_resolution_bounding_box() {
|
||||
let eps = splice(&red_eps(80, 50, "\n"), b"%%EndComments", b"%%HiResBoundingBox: 0.5 0.5 79.5 49.5\n%%EndComments");
|
||||
let (_, p, _, r) = one_placed(&placed_eps_file(&eps));
|
||||
assert_eq!((p.width, p.height), (79.0, 49.0));
|
||||
// The box's top left corner is the file's (0.5, 49.5), where the matrix puts it.
|
||||
let m = Affine::new([5.0, 0.0, 0.0, -5.0, 0.0, 200.0]);
|
||||
let (got, want) = (p.xf * Point::ZERO, r.to_doc * m * Point::new(0.5, 49.5));
|
||||
assert!((got - want).hypot() < 1e-9, "{got:?} {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_files_box_with_its_corners_reversed_leaves_it_unread() {
|
||||
let data = splice(&placed_eps_file(&red_eps(80, 50, "\n")), b"0 0 80 50 4 4 0", b"80 50 0 0 4 4 0");
|
||||
let r = read(&data).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_included_eps_files_own_last_line_end_is_kept() {
|
||||
// The data's line end after the file's own is taken off; a single one is the file's.
|
||||
let (lf, crlf) = ("%!PS\n%%BoundingBox: 0 0 80 50\n%%EOF\n", "%!PS\r\n%%BoundingBox: 0 0 80 50\r\n%%EOF\r\n");
|
||||
for (eps, written) in [(lf, format!("{lf}\r")), (lf, lf.to_string()), (crlf, format!("{crlf}\r\n"))] {
|
||||
let data = splice(&placed_eps_file(b"%!@@"), b"%!@@\r%%EndDocument", format!("{written}%%EndDocument").as_bytes());
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), eps, "{written:?}");
|
||||
}
|
||||
// The line end added is the one the `%%BeginDocument:` line ends with: an LF after a file whose
|
||||
// lines end with CR isn't read as a CRLF of the file's.
|
||||
let data =
|
||||
splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", b"shape.eps\n%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r\n%%EndDocument");
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), "%!PS\r%%BoundingBox: 0 0 80 50\r%%EOF\r");
|
||||
// A file whose lines end with CRLF, included as it is after an LF: its last CRLF is its own.
|
||||
let data = splice(&placed_eps_file(b"%!@@"), b"shape.eps\r%!@@\r%%EndDocument", format!("shape.eps\n{crlf}%%EndDocument").as_bytes());
|
||||
let (_, _, blob, _) = one_placed(&data);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), crlf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_eps_file_on_commented_lines_keeps_its_bytes() {
|
||||
let eps = red_eps(80, 50, "\r");
|
||||
let hidden = hide_placed(&placed_eps_file(&eps));
|
||||
let (_, _, blob, _) = one_placed(&hidden);
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the `%_` that starts each line taken off");
|
||||
// The line end added before `%%EndDocument` on a `%_` line of its own.
|
||||
let (_, _, blob, _) = one_placed(&splice(&hidden, b"%%EOF\r\r%_%%EndDocument", b"%%EOF\r%_\r%_%%EndDocument"));
|
||||
assert_eq!(String::from_utf8_lossy(&blob.bytes), String::from_utf8_lossy(&eps), "the added line end taken off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_included_postscript_file_named_as_an_ai_file_stays_unread() {
|
||||
// Read through its name with the artboard its header gives, not the box the placed one shows.
|
||||
for name in ["shape.ai", "SHAPE.AIT"] {
|
||||
let mut data = placed_eps_file(&red_eps(80, 50, "\n"));
|
||||
while data.windows(9).any(|w| w == b"shape.eps") {
|
||||
data = splice(&data, b"shape.eps", name.as_bytes());
|
||||
}
|
||||
let r = read(&data).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{name}: {:?}", art(&r.doc));
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{name}: {:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_eps_with_a_native_document_leaves_the_placed_file_unread() {
|
||||
// Even unreadable native data leaves the file unread: the loader can read an artboard
|
||||
// larger than the EPS bounding box, which would shrink and offset the art when placed.
|
||||
for eol in ["\n", "\r", "\r\n"] {
|
||||
let section = format!("%VectorCraft_BeginData: native \t{eol}%unreadable native data{eol}%VectorCraft_EndData{eol}%%EOF");
|
||||
let eps = splice(&red_eps(80, 50, eol), b"%%EOF", section.as_bytes());
|
||||
let r = read(&placed_eps_file(&eps)).unwrap();
|
||||
assert!(
|
||||
!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))),
|
||||
"included EPS with a native document must stay on the fallback path"
|
||||
);
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn included_bytes_that_arent_an_eps_file_leave_the_placed_file_unread() {
|
||||
// A DCS file, which the placed document reader doesn't read (File › Place makes it a linked
|
||||
// image), stays unread too.
|
||||
let dcs = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%PlateFile: (Black) EPS Local pic.K\n%%EndComments\n%%EOF\n";
|
||||
// An EPS file without a bounding box, whose art is read on a page of another size, stays unread.
|
||||
let boxless = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n1 0 0 setrgbcolor\n0 0 80 50 rectfill\n%%EOF\n";
|
||||
// An EPS file whose program doesn't read draws nothing, so it stays unread too.
|
||||
let broken = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 80 50\n%%EndComments\n0 0 80 50 nosuchoperator\n%%EOF\n";
|
||||
for bytes in [&b"hello\rworld"[..], dcs, boxless, broken] {
|
||||
let r = read(&placed_eps_file(bytes)).unwrap();
|
||||
assert!(!art(&r.doc).iter().any(|n| matches!(n.kind, NodeKind::PlacedDocument(_))), "{:?}", art(&r.doc));
|
||||
assert!(r.unread.iter().any(|(_, kinds)| kinds.iter().any(|k| k == "placed files")), "{:?}", r.unread);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_placed_file_ended_by_comment_stays_hidden() {
|
||||
let mut data = hide_placed(&placed(true, "[5 0 0 -5 0 200]", "/pics/photo.png", None, ""));
|
||||
@@ -3588,6 +3762,7 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> {
|
||||
NodeKind::Group { .. } => "group",
|
||||
NodeKind::Path { .. } => "path",
|
||||
NodeKind::Image(_) => "image",
|
||||
NodeKind::PlacedDocument(_) => "placed",
|
||||
_ => "other",
|
||||
})
|
||||
.collect()
|
||||
@@ -3596,13 +3771,16 @@ fn art_kinds(doc: &Document) -> Vec<&'static str> {
|
||||
#[test]
|
||||
fn version7_placed_file_included_whole_is_read() {
|
||||
// The included document's operators, a `~`, a nested document and counted data in it aren't
|
||||
// the editing data's.
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n1 0 0 setrgbcolor frobnicate ~\n\
|
||||
// the editing data's (the file defines them, so its program reads).
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 10 20 50 50\n%%EndComments\n/frobnicate {} def /~ {} def\n1 0 0 setrgbcolor frobnicate ~\n\
|
||||
%%BeginDocument: inner.eps\n~\n%%EndDocument\n%%BeginData: 14 Binary Bytes\n%%EndDocument\n%%EOF\n";
|
||||
let body = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}%%EndDocument\n~\n");
|
||||
let r = placed_read7(true, &body).unwrap();
|
||||
assert_eq!(art_kinds(&r.doc), ["path"]);
|
||||
assert_unread(&r, "placed files");
|
||||
// A placed document of the file's bytes.
|
||||
assert_eq!(art_kinds(&r.doc), ["placed"]);
|
||||
let NodeKind::PlacedDocument(p) = &art(&r.doc)[0].kind else { panic!() };
|
||||
assert_eq!(r.doc.images[&p.key].bytes.as_slice(), eps.as_bytes());
|
||||
assert!(r.unread.is_empty(), "{:?}", r.unread);
|
||||
// One that doesn't end leaves the layer without its end.
|
||||
let cut = format!("[1 0 0 1 10 20] 10 20 50 50 (art.eps) `\n%%BeginDocument: art.eps\n{eps}~\n");
|
||||
assert!(placed_read7(true, &cut).is_err());
|
||||
|
||||
@@ -50,6 +50,8 @@ mod slots;
|
||||
#[cfg(test)]
|
||||
pub(crate) use build::READ_AFRESH;
|
||||
#[cfg(test)]
|
||||
pub(super) use build::placed_documents;
|
||||
#[cfg(test)]
|
||||
use build::{Frame, MADE, prune_unseen};
|
||||
pub(crate) use build::{MAX_WRAP_WORK, scale_document, scale_symbols};
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -334,6 +334,7 @@ pub(super) fn build_weighing(
|
||||
placeholders,
|
||||
placed_elsewhere,
|
||||
placed_pages,
|
||||
placed_eps,
|
||||
envelopes_drawn,
|
||||
styles_read,
|
||||
text_paints,
|
||||
@@ -644,33 +645,50 @@ pub(super) fn build_weighing(
|
||||
}
|
||||
doc.limit_depth_noting(&mut notes);
|
||||
bind_variables(&mut doc, &bindings, bindings_skipped, &xml_ids, &filled, &mut notes);
|
||||
placed_documents(&mut doc, &placed_pages);
|
||||
if placed_documents(&mut doc, &placed_pages, &placed_eps) && !notes.iter().any(|n| n == ai::LINKED_PREVIEWS) {
|
||||
notes.push(ai::LINKED_PREVIEWS.to_string());
|
||||
}
|
||||
if small.is_some() {
|
||||
scale_read_document(&mut doc, unit, styles_read, symbols_own_size);
|
||||
}
|
||||
Ok((doc, notes))
|
||||
}
|
||||
|
||||
/// The linked images of `pages` that are still in `doc`, opacity-mask art included, as placed
|
||||
/// documents of their page and box, over the same place, each showing the same preview until its
|
||||
/// file is read. An image bound to an image variable stays a linked image, the object an image
|
||||
/// variable binds.
|
||||
fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage]) {
|
||||
if pages.is_empty() {
|
||||
return;
|
||||
/// The linked images of `pages` and included `eps` still in `doc`, opacity-mask art included, as placed
|
||||
/// documents of their page and box. PDF pages keep their previews, and EPS files keep their included
|
||||
/// bytes. An image bound to an image variable stays a linked image, the object an image variable binds.
|
||||
/// Returns whether an included EPS file stays a linked image that way, showing its preview.
|
||||
pub(in crate::import) fn placed_documents(doc: &mut Document, pages: &[ai::PlacedPage], eps: &[ai::PlacedEps]) -> bool {
|
||||
if pages.is_empty() && eps.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let vars = &doc.variables;
|
||||
let image_bound = |id: &NodeId| {
|
||||
vars.bindings.get(id).is_some_and(|names| names.iter().any(|v| vars.variable(v).is_some_and(|v| v.kind == VariableKind::Image)))
|
||||
};
|
||||
let pages: std::collections::HashMap<NodeId, ai::PlacedPage> = pages.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, *p)).collect();
|
||||
let previews = eps.iter().any(|p| image_bound(&p.id));
|
||||
let eps: std::collections::HashMap<NodeId, &ai::PlacedEps> = eps.iter().filter(|p| !image_bound(&p.id)).map(|p| (p.id, p)).collect();
|
||||
for layer in &mut doc.layers {
|
||||
to_placed_documents(Arc::make_mut(layer), &pages);
|
||||
to_placed_documents(Arc::make_mut(layer), &pages, &eps, &mut doc.images);
|
||||
}
|
||||
previews
|
||||
}
|
||||
|
||||
/// [`placed_documents`] in `n` and everything in it.
|
||||
fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap<NodeId, ai::PlacedPage>) {
|
||||
fn to_placed_documents(
|
||||
n: &mut Node,
|
||||
pages: &std::collections::HashMap<NodeId, ai::PlacedPage>,
|
||||
eps: &std::collections::HashMap<NodeId, &ai::PlacedEps>,
|
||||
images: &mut std::collections::BTreeMap<String, vectorcraft_doc::ImageBlob>,
|
||||
) {
|
||||
if let Some(eps) = eps.get(&n.id)
|
||||
&& let NodeKind::Image(im) = &n.kind
|
||||
&& im.link.is_some()
|
||||
{
|
||||
images.entry(eps.placed.key.clone()).or_insert_with(|| eps.blob.clone());
|
||||
n.kind = NodeKind::PlacedDocument(Box::new(eps.placed.clone()));
|
||||
}
|
||||
// A box too small to take the image's pixels to (its transform not finite) keeps the linked image.
|
||||
if let Some(page) = pages.get(&n.id)
|
||||
&& let NodeKind::Image(im) = &n.kind
|
||||
@@ -694,10 +712,10 @@ fn to_placed_documents(n: &mut Node, pages: &std::collections::HashMap<NodeId, a
|
||||
n.kind = NodeKind::PlacedDocument(Box::new(placed));
|
||||
}
|
||||
if let Some(m) = n.extras_if_any().and_then(|e| e.mask.as_mut()) {
|
||||
to_placed_documents(Arc::make_mut(&mut m.art), pages);
|
||||
to_placed_documents(Arc::make_mut(&mut m.art), pages, eps, images);
|
||||
}
|
||||
for c in n.children_mut().into_iter().flatten() {
|
||||
to_placed_documents(Arc::make_mut(c), pages);
|
||||
to_placed_documents(Arc::make_mut(c), pages, eps, images);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1905,11 +1923,12 @@ fn outside_placed_files(objects: &[Vec<Arc<Node>>], doc: &Document, placed: &[(N
|
||||
}
|
||||
|
||||
/// Where the placed files that show in `nodes` are: the linked images the editing data's reader
|
||||
/// makes of them.
|
||||
/// makes of them, and the placed documents it makes of the EPS files whose bytes it includes.
|
||||
fn placed_files(nodes: &[Arc<Node>], out: &mut Vec<Rect>) {
|
||||
for n in nodes.iter().filter(|n| n.visible) {
|
||||
match &n.kind {
|
||||
NodeKind::Image(im) if im.link.is_some() => out.extend(n.visual_bounds()),
|
||||
NodeKind::PlacedDocument(_) => out.extend(n.visual_bounds()),
|
||||
_ => {
|
||||
if let Some(c) = n.children() {
|
||||
placed_files(c, out);
|
||||
|
||||
@@ -56,6 +56,19 @@ fn tree(nodes: &[Arc<Node>]) -> String {
|
||||
nodes.iter().map(one).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// Placed EPS files drawn as the app draws them: the art of the file read as it opens, in its
|
||||
/// bounding box (the engine registers the app's own loader).
|
||||
fn draw_placed_eps() {
|
||||
fn load(_: &vectorcraft_doc::PlacedDocument, bytes: &[u8]) -> Option<(vectorcraft_doc::Document, Node, Rect)> {
|
||||
let mut doc = import(bytes).ok()?.document;
|
||||
let frame = doc.artboards.first()?.rect;
|
||||
let layers = std::mem::take(&mut doc.layers);
|
||||
let children = layers.iter().flat_map(|l| l.children().map(|c| c.to_vec()).unwrap_or_default()).collect();
|
||||
Some((doc, Node::new(vectorcraft_doc::NodeId(0), NodeKind::Group { children, clip: false }), frame))
|
||||
}
|
||||
vectorcraft_doc::placed_document::set_loader(load);
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -424,9 +437,10 @@ fn a_postscript_ai_with_a_template_box_and_no_art_size_opens_on_a_letter_artboar
|
||||
}
|
||||
|
||||
/// 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.
|
||||
/// included whole: the layers come in, the placed file as a placed document of its bytes in its box.
|
||||
#[test]
|
||||
fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
|
||||
draw_placed_eps();
|
||||
// `` ` `` 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";
|
||||
@@ -440,14 +454,35 @@ fn a_legacy_file_with_a_placed_eps_comes_in_through_its_layers() {
|
||||
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);
|
||||
let NodeKind::PlacedDocument(p) = &art[1].kind else { panic!("{}: {:?}", tree(art), r.warnings) };
|
||||
assert_eq!(r.document.images[&p.key].bytes.as_slice(), eps.as_bytes(), "the file's bytes");
|
||||
assert_eq!(p.link.path, "art.eps");
|
||||
// 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);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A legacy file whose placed EPS file, included whole, has type: the page's type is the placed
|
||||
/// file's, so the layers come in with it as a placed document.
|
||||
#[test]
|
||||
fn a_legacy_file_with_a_placed_eps_with_type_comes_in_through_its_layers() {
|
||||
draw_placed_eps();
|
||||
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\n\
|
||||
/Helvetica findfont 12 scalefont setfont 15 30 moveto (Hi) show\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();
|
||||
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!(matches!(art[1].kind, NodeKind::PlacedDocument(_)), "{}: {:?}", tree(art), r.warnings);
|
||||
}
|
||||
|
||||
/// A legacy file with a linked image (version 7 specification §8.2, §8.3: `(path) modified XG`, then
|
||||
|
||||
@@ -8358,6 +8358,119 @@ fn a_placed_pdf_page_bound_to_an_image_variable_stays_a_linked_image() {
|
||||
assert_eq!(d.variables.objects_of("v_file"), [n.id], "{notes:?}");
|
||||
}
|
||||
|
||||
/// An included EPS keeps its linked preview and binding when an image variable binds it.
|
||||
#[test]
|
||||
fn a_placed_eps_with_a_preview_preserves_its_image_variable_binding() {
|
||||
use vectorcraft_testkit::ai::{XmlValue, variable_library_data, xml_element, xml_node};
|
||||
let declared = vec![xml_node(
|
||||
1,
|
||||
"variable",
|
||||
XmlValue::Str(""),
|
||||
&[("trait", XmlValue::Str("fileref")), ("varName", XmlValue::Unicode("v_file")), ("docRef", XmlValue::Raw("/XMLUIDREF : (eps) ;"))],
|
||||
&[],
|
||||
)];
|
||||
let set = xml_element("variableSet", &[("locked", "none")], &[xml_element("variables", &[], &declared)]);
|
||||
let library = variable_library_data(&xml_element("variableSets", &[], &[set]));
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n";
|
||||
let place = format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\
|
||||
%%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n\
|
||||
%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n~\n%AI5_EndPlace\n\
|
||||
%_/ArtDictionary :\n%_/XMLUID : (eps) ; (AI10_ArtUID) ,\n%_;\n%_\n",
|
||||
"\x7f\0\0\0".repeat(4)
|
||||
);
|
||||
let art = layer("Jig", true, &place);
|
||||
let (bound, notes) = crate::ai_alone(&private(&native(&(library + &art)))).unwrap();
|
||||
let n = &bound.layers[0].children().unwrap()[0];
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) };
|
||||
assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps");
|
||||
assert_eq!((im.width, im.height), (2, 2));
|
||||
assert_eq!(bound.images[&im.key].mime, "image/png");
|
||||
assert!(bound.images.values().all(|b| b.mime != "application/postscript"));
|
||||
assert_eq!(bound.variables.objects_of("v_file"), [n.id], "{notes:?}");
|
||||
assert!(!notes.iter().any(|n| n.contains("variable bindings")), "{notes:?}");
|
||||
assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "the preview it shows is noted: {notes:?}");
|
||||
let (unbound, notes) = crate::ai_alone(&private(&native(&art))).unwrap();
|
||||
assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "it draws its bytes: {notes:?}");
|
||||
let converted = &unbound.layers[0].children().unwrap()[0];
|
||||
assert_eq!(converted.id, n.id);
|
||||
let NodeKind::PlacedDocument(p) = &converted.kind else { panic!("{:?} {notes:?}", converted.kind) };
|
||||
assert_eq!(&*unbound.images[&p.key].bytes, eps.as_bytes());
|
||||
assert!(unbound.images[&p.key].proxy.is_none());
|
||||
}
|
||||
|
||||
/// What reading an included EPS file warns of, such as art left out, is in the open result.
|
||||
#[test]
|
||||
fn a_placed_eps_read_in_part_warns_of_what_it_leaves_out() {
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 30 30 rectfill\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
let own = crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).unwrap().warnings;
|
||||
assert!(!own.is_empty(), "the file read alone warns");
|
||||
for place in [placed_eps_with_preview(eps), placed_eps_with_preview(eps).replace(&placed_eps_preview(), "")] {
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap();
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
assert!(matches!(n.kind, NodeKind::PlacedDocument(_)), "{:?} {notes:?}", n.kind);
|
||||
for w in &own {
|
||||
assert!(notes.contains(&format!("a placed EPS file: {w}")), "{w}: {notes:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An unreadable included EPS keeps the preview that the linked image can show.
|
||||
#[test]
|
||||
fn a_placed_eps_with_an_unreadable_program_keeps_its_preview() {
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 60 60\n%%EndComments\n0 0 60 60 nosuchoperator\n%%EOF\n";
|
||||
assert!(crate::import_names(eps.as_bytes(), true, false, crate::NameEncoding::default()).is_err());
|
||||
let place = placed_eps_with_preview(eps);
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&layer("Jig", true, &place)))).unwrap();
|
||||
let n = &d.layers[0].children().unwrap()[0];
|
||||
let NodeKind::Image(im) = &n.kind else { panic!("{:?} {notes:?}", n.kind) };
|
||||
assert_eq!(im.link.as_ref().unwrap().path, "/files/shape.eps");
|
||||
assert_eq!((im.width, im.height), (2, 2));
|
||||
let preview = &d.images[&im.key];
|
||||
assert_eq!(preview.mime, "image/png");
|
||||
assert_eq!(preview.proxy.as_deref(), Some(&*preview.bytes));
|
||||
assert!(d.images.values().all(|b| b.mime != "application/postscript"));
|
||||
assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}");
|
||||
}
|
||||
|
||||
/// A pattern's included EPS keeps its bytes without waiting for image variable binding.
|
||||
#[test]
|
||||
fn a_placed_eps_with_a_preview_in_a_pattern_keeps_its_bytes() {
|
||||
let eps = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 rectfill\n%%EOF\n";
|
||||
let place = placed_eps_with_preview(eps);
|
||||
let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{place}E\n%AI3_EndPattern\n");
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap();
|
||||
let art = &d.pattern("Pic").unwrap().art;
|
||||
assert_eq!(art.len(), 1, "{art:?} {notes:?}");
|
||||
let NodeKind::PlacedDocument(p) = &art[0].kind else { panic!("{art:?} {notes:?}") };
|
||||
assert_eq!(&*d.images[&p.key].bytes, eps.as_bytes());
|
||||
assert_eq!(d.images[&p.key].mime, "application/postscript");
|
||||
assert!(d.images[&p.key].proxy.is_none());
|
||||
assert!(!notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}");
|
||||
|
||||
// One whose bytes can't be read keeps its preview there too.
|
||||
let broken = "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 40 40\n%%EndComments\n0 0 40 40 nosuchoperator\n%%EOF\n";
|
||||
let pattern = format!("%AI3_BeginPattern: (Pic)\n(Pic) 0 0 40 40\n{}E\n%AI3_EndPattern\n", placed_eps_with_preview(broken));
|
||||
let (d, notes) = crate::ai_alone(&private(&native(&(pattern + &layer("Jig", true, &square(10, 10)))))).unwrap();
|
||||
let art = &d.pattern("Pic").unwrap().art;
|
||||
assert!(matches!(&art[..], [n] if matches!(&n.kind, NodeKind::Image(im) if im.link.is_some())), "{art:?} {notes:?}");
|
||||
assert!(notes.iter().any(|n| n.contains("low-resolution preview")), "{notes:?}");
|
||||
}
|
||||
|
||||
/// A placed EPS file at `/files/shape.eps` whose bytes `eps` the data includes, with a 2 × 2 preview.
|
||||
fn placed_eps_with_preview(eps: &str) -> String {
|
||||
format!(
|
||||
"%AI5_BeginPlace\n%%FileType: 0\n[1 0 0 -1 30 70] 0 0 40 40 4 4 0\n(/files/shape.eps)`\n\
|
||||
%%BeginDocument: /files/shape.eps\n{eps}\n%%EndDocument\n{}~\n%AI5_EndPlace\n",
|
||||
placed_eps_preview()
|
||||
)
|
||||
}
|
||||
|
||||
/// The 2 × 2 preview of [`placed_eps_with_preview`].
|
||||
fn placed_eps_preview() -> String {
|
||||
format!("%AI26_BeginPlacedObjectPreview\n2 2 8 32 17 {}\n%AI26_EndPlacedObjectPreview\n", "\x7f\0\0\0".repeat(4))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_placed_file_goes_where_it_draws_closer_to_the_page() {
|
||||
// A 2 × 2 placed file (a small logo on a large page) whose box corner the matrix takes to
|
||||
|
||||
@@ -61,6 +61,18 @@ pub use print::{PrintFonts, PrintJob, PrintPage, print};
|
||||
use vectorcraft_doc::Document;
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
std::thread_local! {
|
||||
/// Included EPS files parsed by open checks on this thread.
|
||||
pub(crate) static INCLUDED_EPS_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Included EPS files parsed by open checks on this thread, for tests that count work instead of timing it.
|
||||
#[cfg(any(test, feature = "work-count"))]
|
||||
pub fn included_eps_reads() -> usize {
|
||||
INCLUDED_EPS_READS.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// The PostScript language level the file needs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Level {
|
||||
|
||||
@@ -2443,6 +2443,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392).
|
||||
Placed (linked) files in a `.ai`'s editing data come in as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (a file found next to the document or at its path is read as the document opens). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line, the frame made taller with a warning in the open result (#1392).
|
||||
A placed PDF or `.ai` file in a `.ai`'s editing data comes in as a placed document instead of a linked image: it shows the page and Crop to box its dictionary names, and the preview the file keeps until its file is found, then the page as vectors. A placed file in opacity-mask art keeps showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`).
|
||||
A placed EPS file whose bytes a `.ai`'s editing data includes (between `%%BeginDocument:` and `%%EndDocument`) comes in as a placed document of those bytes in its bounding box: it draws its art whether or not its file is found, a native save keeps the bytes, File › Package with Copy Fonts reads its type for the fonts it copies, and a file found unchanged is neither missing nor modified. The placed file stays as before when its bytes are larger than 256 MiB, are a DCS file, have no bounding box of their own, carry a VectorCraft document, don't read as an EPS file, or belong to a file named `.ai` or `.ait`, and a placed EPS file with a preview that an image variable binds stays the linked image showing its preview (`crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/placed_document.rs`).
|
||||
In a `.ai` or EPS opened from its editing data, and in a legacy `.ai`, each anchor is smooth or a corner as the case of the segment operator ending on it says (`l`, `c`, `v`, `y` smooth; `L`, `C`, `V`, `Y` corner), and a closed path's first anchor takes the case of the segment back to it; points and handles stay where they are. Paths, compound paths, clipping paths, guide paths, area type frames and type-on-a-path paths all keep it (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/legacy_ai/tests.rs`).
|
||||
In `.ai` and EPS editing-data import, a clipping group, layer or opacity mask's art with several clipping paths (`W`) clips to their intersection: each clipping path after the first clips a clipping group nested inside the one before it, and each keeps its own stroke and transparency. A compound path of clipping paths (`*u` … `*U`) is still one clipping path, and clipping paths that would nest the art past the document's 32 levels stop the editing data from being read (`crates/eps/src/import/ai/tests.rs`).
|
||||
`.ai` and EPS editing-data import keeps template layers, and opens canvas and artboard ruler guides as ruler guides on their layers; guide objects stay editable guide paths (#779; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`).
|
||||
|
||||
Reference in new issue
Block a user