Fix #735: Illustrator EPS and .ai files match their page in Fit to Artwork Bounds and the page check

- Fit to Artwork Bounds fits the art exports draw: hidden objects and
  layers, guides and template layers don't count, and the bounds stop at
  a layer's clip.
- The comparison with the page catches an object one draws that the
  other doesn't (pixels whose neighbours all differ, away from type), a
  light colour against white, and, for an EPS whose page is its art's
  box, art the layers print outside it.
- textAs: outlines opens a .ai whose type shows from its PDF part, which
  has the outlines.
- document.open takes editingData: false to open an Illustrator EPS or
  .ai as its page or PDF part only, for print pipelines.

Part of #637.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatastic 2026-10-09 18:52:54 +07:00
parent 569b4ac240
commit c599522061
21 changed files with 413 additions and 65 deletions

File diff suppressed because one or more lines are too long

View File

@ -137,11 +137,12 @@ pub fn load(name: &str, bytes: &[u8]) -> Result<Loaded> {
/// layers and hidden objects as they were, and the art outside its artboard (its PDF part has
/// only what is on the artboards), as an EPS of the editor is read. Anything else as it was.
fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warnings: Vec<String>) -> (Document, Vec<String>) {
if opts.pages.is_some() || !opts.layers {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return (doc, warnings);
}
let Some(private) = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref()) else { return (doc, warnings) };
let (doc, mut warnings) = vectorcraft_eps::layered_ai(&private, doc, warnings);
let outlined = opts.text_as == vectorcraft_pdf::TextAs::Outlines;
let (doc, mut warnings) = vectorcraft_eps::layered_ai(&private, doc, warnings, outlined);
// The note that the art outside the artboard is lost is the reason the layers weren't read.
if warnings.iter().any(|w| w.starts_with("the file's layers weren't read from its editing data")) {
return (doc, warnings);
@ -151,10 +152,10 @@ fn through_editing_data(bytes: &[u8], opts: &LoadOptions, doc: Document, warning
}
/// A `.ai` saved without PDF compatibility (its PDF part is a placeholder page) from the editor's
/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers are
/// off), an error when it can't be read.
/// own copy of its art alone: `None` when the file has none (or pages are picked, or layers or the
/// editing data are off), an error when it can't be read.
fn from_editing_data_alone(bytes: &[u8], opts: &LoadOptions) -> Option<Result<(Document, Vec<String>)>> {
if opts.pages.is_some() || !opts.layers {
if opts.pages.is_some() || !opts.layers || !opts.editing_data {
return None;
}
let private = vectorcraft_pdf::illustrator_data(bytes, opts.password.as_deref())?;
@ -178,7 +179,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
_ if format.id == "eps" || vectorcraft_pdf::is_postscript(bytes) => {
let editing = vectorcraft_eps::has_native(bytes).then_some((true, || vectorcraft_eps::native(bytes)));
restore_or_import(editing, || {
let r = vectorcraft_eps::import(bytes).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
let r = vectorcraft_eps::import_with(bytes, opts.editing_data).map_err(|e| err(format!("can't open `{}`: {e}", file_name(name))))?;
Ok((r.document, r.warnings))
})?
}

View File

@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Open Document",
[],
None,
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
"{path} or {name, dataBase64}, PDF/.ai: pages?: \"2-3, 5\" (1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page) | false (one layer per page, without the art that is off; Save then asks for a name), editingData?: true (default: an EPS or .ai that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai whose type shows opens from its PDF part with textAs: outlines) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), DXF: dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} → {index, title, format, warnings, restored, missingLinks, modifiedLinks, updatedLinks: [{name, path, ids}]}; any readable format (see document.formats): .vectorcraft/.drawcraft, .svg/.svgz, .pdf/.ai, .ait, ASCII .dxf (each DXF layer with art a layer; blocks symbols; what can't come in is listed in warnings), PNG/JPEG/GIF/WebP/TIFF/BMP (an image opens as a document of its size at the resolution it declares, as file.place sizes it; 72 ppi, 1 px = 1 pt, when it declares none), .emf/.wmf (one artboard, the picture's frame; records VectorCraft doesn't read are skipped with one warning), .eps and PostScript .ai (one artboard, the bounding box: an EPS file VectorCraft wrote restores the document it carries, restored: true; other files are read by a PostScript interpreter — paths, colours and spot inks, clips, gradients, images, type in the fonts named — and come in as their TIFF preview, with a warning, when their PostScript can't be read). A PDF/.ai/.ait or SVG saved with Preserve Editing restores the native document it carries (restored: true; a PDF only when no pages are picked), unless the file was changed elsewhere since or the data can't be read: then its artwork is imported and the first warning says why. Templates (native templates, .ait) open as a new untitled document; a restored .ai keeps its path (Save writes .ai again). Linked images are read from their files (looked for at their path, then relative to the document): missing ones show their saved preview (links.relink), modified ones are read again only with Preferences › Update Links: Automatically (else links.update). An SVG's <image> files (relative links from the SVG's folder) stay linked, SVG files become art, missing ones a placeholder in their box (a warning and missingLinks)",
always,
load::open
),

View File

@ -32,6 +32,10 @@ pub struct LoadOptions {
pub layers: bool,
/// How a DXF drawing comes in (the `dxf` param, see [`super::dxfimport`]).
pub dxf: vectorcraft_cad::ImportOptions,
/// An Illustrator EPS or `.ai` that carries the editing copy of its art opens from it (its
/// layers, hidden objects and the art outside its artboards); else only what its page or PDF
/// part prints comes in.
pub editing_data: bool,
}
impl Default for LoadOptions {
@ -45,6 +49,7 @@ impl Default for LoadOptions {
text_as: TextAs::default(),
layers: true,
dxf: Default::default(),
editing_data: true,
}
}
}
@ -52,7 +57,8 @@ impl Default for LoadOptions {
impl LoadOptions {
/// From command params: `pages` (`"2-3, 5"`, a page number or `"all"`), `page` (one page, when
/// `pages` isn't given), `cropTo` (or `crop`), `password`, `colorMode` (`rgb` | `cmyk`) with `grays`,
/// `textAs` (`text` | `outlines`), `layers` (true | false) and `dxf` (the DXF import options).
/// `textAs` (`text` | `outlines`), `layers` (true | false), `editingData` (true | false) and `dxf`
/// (the DXF import options).
pub fn from_params(cmd: &str, p: &Value) -> Result<Self> {
let pages = match p.get("pages").filter(|v| !v.is_null()).or_else(|| p.get("page").filter(|v| !v.is_null())) {
None => None,
@ -75,8 +81,12 @@ impl LoadOptions {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "layers must be true or false"))?,
};
let editing_data = match p.get("editingData").filter(|v| !v.is_null()) {
None => true,
Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "editingData must be true or false"))?,
};
let dxf = super::dxfimport::options(cmd, p.get("dxf"))?;
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf })
Ok(Self { pages, crop, password, color_mode, grays, text_as, layers, dxf, editing_data })
}
/// Does the document read only part of the file, or read it differently (a page range, another

View File

@ -108,3 +108,52 @@ fn an_ai_file_saved_without_its_pdf_part_opens_from_its_editing_data() {
let e = open(&mut s, "plain.ai", &ai::ai(b"", PLACEHOLDER), json!({})).unwrap_err().to_string();
assert!(e.contains("placeholder"), "{e}");
}
#[test]
fn editing_data_false_opens_only_what_the_page_prints() {
let mut s = Session::new();
for (name, file) in [("art.eps", ai::eps(&ai::sample_data(), ai::page_ps())), ("art.ai", ai::ai(&compressed(&ai::sample_data()), ai::page_pdf()))]
{
let r = open(&mut s, name, &file, json!({"editingData": false})).unwrap();
let layers = &s.doc().unwrap().doc.layers;
assert_eq!(layers.len(), 1, "{name}: {r}");
assert_ne!(names(layers), ["Art"], "{name}: the page's layer");
}
let e = open(&mut s, "art.eps", &ai::eps(&ai::sample_data(), ai::page_ps()), json!({"editingData": "no"})).unwrap_err().to_string();
assert!(e.contains("editingData must be true or false"), "{e}");
// A file that is only its editing data can't open without it.
let e = open(&mut s, "art.ai", &ai::ai(&compressed(&ai::sample_data()), PLACEHOLDER), json!({"editingData": false})).unwrap_err().to_string();
assert!(e.contains("placeholder"), "{e}");
}
#[test]
fn fit_to_artwork_bounds_leaves_out_the_hidden_art_and_guides_the_editing_data_has() {
// A shown square; a hidden one and a long guide far from it, which the page doesn't draw.
let art =
format!("0 g\n{}f\n1 Xw\n{}f\n0 Xw\n-500 20 m\n700 20 L\n(N) *\n", ai::rect(10.0, 10.0, 50.0, 50.0), ai::rect(150.0, 60.0, 190.0, 95.0));
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &art));
let mut s = Session::new();
let r = open(&mut s, "fit.eps", &ai::eps(data.as_bytes(), "0 setgray 10 10 40 40 rectfill\n"), json!({})).unwrap();
let layer = &s.doc().unwrap().doc.layers[0];
let kids = layer.children().unwrap();
assert_eq!(kids.len(), 3, "{r}");
assert!(!kids[1].visible && matches!(kids[2].kind, NodeKind::Path { guide: true, .. }));
s.execute("artboard.fitToArt", &json!({})).unwrap();
// The square, 50 to 90 down the 100-point page.
assert_eq!(s.doc().unwrap().doc.artboards[0].rect, vectorcraft_geom::Rect::new(10.0, 50.0, 50.0, 90.0));
}
#[test]
fn type_asked_for_as_outlines_opens_a_file_whose_type_shows_from_its_pdf_part() {
let text = "/AI11Text :\n0 /FreeUndo ,\n0 /FrameIndex ,\n0 /StoryIndex ,\n;\n";
let data = ai::editing_data(200.0, 100.0, &ai::layer("Art", &format!("0 g\n{}f\n{text}", ai::rect(10.0, 10.0, 50.0, 50.0))));
let file = ai::ai(&compressed(data.as_bytes()), "0 g 10 10 40 40 re f BT /F1 12 Tf 100 50 Td (Hi) Tj ET");
let mut s = Session::new();
// As type, the page's type goes into the text object of the layers.
let r = open(&mut s, "type.ai", &file, json!({})).unwrap();
assert_eq!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
// As outlines, only the PDF part has them.
let r = open(&mut s, "type.ai", &file, json!({"textAs": "outlines"})).unwrap();
assert!(r["warnings"].to_string().contains("outlines"), "{r}");
assert_ne!(names(&s.doc().unwrap().doc.layers), ["Art"], "{r}");
}

View File

@ -139,7 +139,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_doc,
artboard_set
),
cmd!("artboard.fitToArt", "Fit to Artwork Bounds", ["Object", "Artboards"], None, "{index?}", has_doc, artboard_fit_art),
cmd!(
"artboard.fitToArt",
"Fit to Artwork Bounds",
["Object", "Artboards"],
None,
"{index?} the artboard fits the art that shows (with its strokes and effects; hidden objects and layers, guides and template layers don't count)",
has_doc,
artboard_fit_art
),
cmd!("artboard.fitToSelection", "Fit to Selected Art", ["Object", "Artboards"], None, "{index?}", has_selection, artboard_fit_sel),
cmd!(
"layer.clippingMask.toggle",
@ -810,9 +818,11 @@ fn rect_map(from: Rect, to: Rect) -> Option<Affine> {
xf.is_finite().then_some(xf)
}
/// The artboard fits the art that exports draw: hidden objects and layers, guides and template
/// layers don't count.
fn artboard_fit_art(s: &mut Session, p: &Value) -> Result<Value> {
let i = p.get("index").and_then(Value::as_u64).unwrap_or(0) as usize;
let b = s.doc()?.doc.art_bounds().ok_or_else(|| EngineError::Other("no artwork".into()))?;
let b = vectorcraft_render::encode::art_bounds(&s.doc()?.doc).ok_or_else(|| EngineError::Other("no artwork".into()))?;
s.execute("artboard.setProps", &json!({"index": i, "x": b.x0, "y": b.y0, "width": b.width(), "height": b.height()}))
}

View File

@ -1731,7 +1731,7 @@ proptest! {
*x = b;
}
}
survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![]).0))?;
survive("mutated .ai editing data", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false).0))?;
}
}
@ -1886,9 +1886,13 @@ proptest! {
fn ai_hostile_editing_data_never_panics(tokens in prop::collection::vec(arb_ai_token(), 0..80)) {
use vectorcraft_testkit::ai;
let data = ai::editing_data(200.0, 100.0, &format!("%AI5_BeginLayer\n1 1 1 1 0 0 1 0 79 128 255 0 50 0 Lb\n(L) Ln\n{}\nLB\n", tokens.join(" ")));
survive("hostile editing data", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![]).0))?;
survive("hostile editing data", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], false).0))?;
survive("hostile editing data, type as outlines", || Some(vectorcraft_eps::layered_ai(data.as_bytes(), Document::new(200.0, 100.0), vec![], true).0))?;
let eps = ai::eps(data.as_bytes(), ai::page_ps());
survive("hostile editing data in an EPS", || vectorcraft_engine::cmd::fileio::load("x.eps", &eps).ok().map(|l| l.doc))?;
// An EPS whose page is its art's box, not its artboard: what prints outside it is compared too.
let boxed = ai::eps(data.replace("%AI3_Cropmarks: 0 0 200 100", "%AI3_Cropmarks: -50 -50 300 200").as_bytes(), ai::page_ps());
survive("hostile editing data in an EPS of its art's box", || vectorcraft_engine::cmd::fileio::load("x.eps", &boxed).ok().map(|l| l.doc))?;
}
/// The testkit's sample damaged, as it is and compressed, in EPS and `.ai` files.

View File

@ -166,8 +166,15 @@ fn reason(e: &PsError, fault: Option<&Fault>) -> String {
}
}
/// Read an EPS or PostScript file (its first page).
/// Read an EPS or PostScript file (its first page), an Illustrator EPS through the editing copy of
/// its art when it carries one (see `native`).
pub fn import(bytes: &[u8]) -> Result<Imported, String> {
import_with(bytes, true)
}
/// [`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> {
let (ps, _) = crate::sections(bytes).ok_or("the file's preview header points outside the file")?;
if !ps.starts_with(b"%!") {
return Err("this is not a PostScript file".into());
@ -189,7 +196,8 @@ pub fn import(bytes: &[u8]) -> Result<Imported, String> {
}
let drew = !out.drawn.is_empty();
let why = match (&result, drew) {
(Ok(()), true) => return Ok(native::layered(ps, finish(out))),
(Ok(()), true) if editing_data => return Ok(native::layered(ps, finish(out))),
(Ok(()), true) => return Ok(finish(out)),
(Ok(()), false) => "it draws nothing VectorCraft's PostScript reader can show".to_string(),
(Err(e), _) => reason(e, fault.as_ref()),
};

View File

@ -15,7 +15,9 @@
//!
//! What a layer that shows has that `ai` doesn't read makes the file come in as its page, as it did
//! before; on a layer that doesn't show it is left out of that layer, with a warning. The page is
//! also the safety net: when the layers' art looks different from it, the page is used.
//! also the safety net: when the layers' art looks different from it (one draws an object the
//! other doesn't, or much of it differs; an EPS whose page is its art's box has nothing printed
//! outside it), the page is used.
//!
//! Where a file doesn't match what this module expects, it is left alone and its page is imported.
@ -550,10 +552,49 @@ fn as_printed(doc: &Document) -> Option<Document> {
hide(&mut d.layers).then_some(d)
}
/// The lightness (0 to 255, Rec. 601 weights) of a premultiplied pixel seen on white.
fn lightness(p: &[u8; 4]) -> u8 {
let on_white = |c: u8| u32::from(c) + 255 - u32::from(p[3]).min(255);
((on_white(p[0]) * 299 + on_white(p[1]) * 587 + on_white(p[2]) * 114) / 1000).min(255) as u8
/// A premultiplied pixel seen on white.
fn on_white(p: &[u8; 4]) -> [u32; 3] {
let paper = 255 - u32::from(p[3]).min(255);
[0, 1, 2].map(|i| (u32::from(p[i]) + paper).min(255))
}
/// The lightness (0 to 255, Rec. 601 weights) of a pixel seen on white.
fn lightness([r, g, b]: [u32; 3]) -> u32 {
(r * 299 + g * 587 + b * 114) / 1000
}
/// How far (0 to 255) a pixel seen on white is from white: how much ink it has.
fn ink([r, g, b]: [u32; 3]) -> u32 {
255 - r.min(g).min(b)
}
/// How far apart two pixels' lightness, or their ink where one is white, may be for them to look
/// alike.
const SAME_PIXEL: u32 = 48;
/// The most ink a pixel seen as white has.
const WHITE: u32 = 8;
/// Do two pixels look different: in lightness, or one inked (as a light yellow is) where the other
/// is white?
fn differ(p: &[u8; 4], q: &[u8; 4]) -> bool {
let (p, q) = (on_white(p), on_white(q));
let (a, b) = (ink(p), ink(q));
lightness(p).abs_diff(lightness(q)) > SAME_PIXEL || (a.min(b) <= WHITE && a.abs_diff(b) > SAME_PIXEL)
}
/// How much two documents draw differently: the share (0 to 1) of the pixels that differ, and of
/// those whose neighbours all differ too, away from type (where one draws an object that the other
/// doesn't, not the edges of one drawn a little differently, or type laid out a little
/// differently: a line the page sets in pieces is laid out afresh as one).
#[derive(Clone, Copy)]
struct Difference {
any: f64,
solid: f64,
}
/// The scale the comparisons draw a region at: about 400 pixels along its longer side.
fn compare_scale(r: Rect) -> f64 {
(400.0 / r.width().max(r.height()).max(1.0)).min(4.0)
}
/// The page drawn once, to weigh the layers' art against it: [`Self::difference`] draws the layers
@ -561,6 +602,8 @@ fn lightness(p: &[u8; 4]) -> u8 {
/// can share their keys and not their pixels, so the two don't share one).
struct PageView {
page: vectorcraft_render::Rendered,
/// Where the page's own type is, in its pixels.
page_type: Vec<Rect>,
layers: vectorcraft_render::Renderer,
scale: f64,
}
@ -568,36 +611,118 @@ struct PageView {
impl PageView {
fn new(frame: &Frame<'_>) -> Self {
let ra = frame.page_rect;
let scale = (400.0 / ra.width().max(ra.height()).max(1.0)).min(4.0);
let scale = compare_scale(ra);
// Drawn on nothing and then seen on white: blending modes have no page to blend with, as in
// the app that wrote the file.
let page = vectorcraft_render::Renderer::new().render_region(frame.page, ra, scale, false);
Self { page, layers: vectorcraft_render::Renderer::new(), scale }
let mut page_type = vec![];
type_areas(&frame.page.layers, ra, scale, &mut page_type);
Self { page, page_type, layers: vectorcraft_render::Renderer::new(), scale }
}
/// How much `b` on `rb` (a rectangle the page's size) draws differently from the page (0 to 1),
/// each seen on white. Pixels are compared by lightness: the page of an RGB document is written in
/// the colours' CMYK equivalents, and what the comparison looks for is art that is missing or out
/// of place.
fn difference(&mut self, b: &Document, rb: Rect) -> f64 {
/// How `b` on `rb` (a rectangle the page's size) draws differently from the page ([`compared`]).
fn difference(&mut self, b: &Document, rb: Rect) -> Difference {
// The page doesn't print what isn't printed.
let printed = as_printed(b);
let b = printed.as_ref().unwrap_or(b);
let (x, y) = (&self.page, self.layers.render_region(b, rb, self.scale, false));
if x.width != y.width || x.height != y.height {
return 1.0;
}
let differing =
x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).filter(|(p, q)| lightness(p).abs_diff(lightness(q)) > 48).count();
differing as f64 / (f64::from(x.width) * f64::from(x.height)).max(1.0)
let y = self.layers.render_region(b, rb, self.scale, false);
let mut areas = self.page_type.clone();
type_areas(&b.layers, rb, self.scale, &mut areas);
compared(&self.page, &y, &areas)
}
}
/// How `a` on `ra` and `b` on `rb` (rectangles of the same size) draw differently ([`compared`]),
/// for a region other than the page's ([`PageView`] draws that one once).
fn difference(a: &Document, ra: Rect, b: &Document, rb: Rect) -> Difference {
let printed = as_printed(b);
let b = printed.as_ref().unwrap_or(b);
let scale = compare_scale(ra);
// A renderer each: the two documents' images can share their keys and not their pixels.
let x = vectorcraft_render::Renderer::new().render_region(a, ra, scale, false);
let y = vectorcraft_render::Renderer::new().render_region(b, rb, scale, false);
let mut areas = vec![];
type_areas(&a.layers, ra, scale, &mut areas);
type_areas(&b.layers, rb, scale, &mut areas);
compared(&x, &y, &areas)
}
/// How two drawings of the same size differ, each drawn on nothing and seen on white, away from
/// the type in `areas` (pixels). Pixels are compared by lightness, and by whether they are inked
/// at all ([`differ`]): the page of an RGB document is written in the colours' CMYK equivalents,
/// and what the comparison looks for is art that is missing or out of place.
fn compared(x: &vectorcraft_render::Rendered, y: &vectorcraft_render::Rendered, areas: &[Rect]) -> Difference {
if x.width != y.width || x.height != y.height {
return Difference { any: 1.0, solid: 1.0 };
}
let differs: Vec<bool> = x.pixels.as_chunks::<4>().0.iter().zip(y.pixels.as_chunks::<4>().0).map(|(p, q)| differ(p, q)).collect();
let (w, h) = (x.width as usize, x.height as usize);
let at = |i: usize, j: usize| j.checked_mul(w).and_then(|row| row.checked_add(i)).and_then(|k| differs.get(k)).copied().unwrap_or(false);
let typed = covered(areas, w, h);
// A pixel on the region's edge has neighbours outside it, which don't count as differing.
let solid = (1..h.saturating_sub(1))
.flat_map(|j| (1..w.saturating_sub(1)).map(move |i| (i, j)))
.filter(|&(i, j)| !typed.get(j * w + i).copied().unwrap_or(true) && (j - 1..=j + 1).all(|n| (i - 1..=i + 1).all(|m| at(m, n))))
.count();
let area = (w as f64 * h as f64).max(1.0);
Difference { any: differs.iter().filter(|d| **d).count() as f64 / area, solid: solid as f64 / area }
}
/// Where the type that shows in `nodes` is, in pixels of `region` drawn at `scale` (with a margin
/// for the strokes round it).
fn type_areas(nodes: &[Arc<Node>], region: Rect, scale: f64, out: &mut Vec<Rect>) {
for n in nodes.iter().filter(|n| n.visible) {
if let NodeKind::Text(_) = n.kind
&& let Some(b) = n.visual_bounds()
{
let px =
|r: Rect| Rect::new((r.x0 - region.x0) * scale, (r.y0 - region.y0) * scale, (r.x1 - region.x0) * scale, (r.y1 - region.y0) * scale);
out.push(px(b.inflate(OUTLINE_REACH, OUTLINE_REACH)));
} else if let Some(c) = n.children() {
type_areas(c, region, scale, out);
}
}
}
/// Which of `w` × `h` pixels (row by row) lie in one of `areas`.
fn covered(areas: &[Rect], w: usize, h: usize) -> Vec<bool> {
// Each area adds one inside it: corners marked, then summed along the rows and down the columns.
let stride = w + 1;
let mut count = vec![0i64; stride * (h + 1)];
let clamp = |v: f64, max: usize| if v.is_finite() { v.clamp(0.0, max as f64) as usize } else { 0 };
for r in areas {
let (x0, y0, x1, y1) = (clamp(r.x0.floor(), w), clamp(r.y0.floor(), h), clamp(r.x1.ceil(), w), clamp(r.y1.ceil(), h));
for (x, y, d) in [(x0, y0, 1), (x1, y0, -1), (x0, y1, -1), (x1, y1, 1)] {
if let Some(c) = count.get_mut(y * stride + x) {
*c += d;
}
}
}
for row in count.chunks_mut(stride) {
let mut run = 0;
for c in row {
run += *c;
*c = run;
}
}
let mut column = vec![0i64; stride];
for row in count.chunks_mut(stride) {
for (c, sum) in row.iter_mut().zip(column.iter_mut()) {
*sum += *c;
*c = *sum;
}
}
(0..h).flat_map(|j| (0..w).map(move |i| (i, j))).map(|(i, j)| count.get(j * stride + i).is_some_and(|c| *c > 0)).collect()
}
/// More of the page than this differing between the layers' art and the page's own, and the
/// layers aren't used.
const MAX_DIFFERENCE: f64 = 0.05;
/// More than this and the import says so.
const NOTABLE_DIFFERENCE: f64 = 0.002;
/// More of the page than this where one draws an object that the other doesn't (see
/// [`Difference`]), and the layers aren't used: about a centimetre square on a letter page.
const MAX_SOLID_DIFFERENCE: f64 = 0.001;
/// Which box of the editing copy is the page.
#[derive(Clone, Copy)]
@ -616,13 +741,17 @@ struct Frame<'a> {
page_rect: Rect,
/// The same area in the layers' document.
rect: Rect,
/// The page holds all the art that prints (an EPS's page is its art's box, unless it was
/// saved as its artboard): the layers print nothing outside it.
whole: bool,
}
/// The document of the editing copy `data`, with the text (and strokes round it) of `visible`, the
/// file read as its page, put in its text objects → the document and its notes. Without a page
/// (a `.ai` saved without its PDF part), its type is made from the file's text document alone and
/// nothing is compared.
fn build(data: &[u8], visible: Option<&Document>, page: Page) -> Result<(Document, Vec<String>), String> {
/// nothing is compared. `outlined`: the page's type was read as outlines, so it has none to put in
/// the text objects.
fn build(data: &[u8], visible: Option<&Document>, page: Page, outlined: bool) -> Result<(Document, Vec<String>), String> {
let Structure { mut doc, to_doc, bbox, artboard, template, hidden_unread, slot_names, warnings } = ai::read(data)?;
let (mut shown, mut hidden) = (vec![], vec![]);
let mut frame = None;
@ -648,10 +777,18 @@ fn build(data: &[u8], visible: Option<&Document>, page: Page) -> Result<(Documen
Arc::make_mut(n).transform(shift, false);
}
}
frame = Some(Frame { page: visible, page_rect, rect });
// An EPS saved as its artboard has the art outside it left out of its page.
let artboard_page =
artboard.is_some_and(|a| [a.x0 - art_box.x0, a.y0 - art_box.y0, a.x1 - art_box.x1, a.y1 - art_box.y1].iter().all(|d| d.abs() <= 1.0));
let whole = matches!(page, Page::Art) && !artboard_page;
frame = Some(Frame { page: visible, page_rect, rect, whole });
}
let mut infos = vec![];
collect_slots(&doc.layers, true, &mut infos);
// Type asked for as outlines is the page's: the text objects that show can't be filled.
if outlined && infos.iter().any(|i| i.shown) {
return Err("its type is to come in as outlines, which only its page has".into());
}
if infos.iter().all(|i| !i.shown) && !shown.is_empty() {
return Err("its page has text, and its layers have no text objects to put it in".into());
}
@ -753,7 +890,7 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u
if found.is_empty() || found.len() > MAX_WEIGHED {
return 0;
}
let mut with = view.difference(doc, rect);
let mut with = view.difference(doc, rect).any;
let mut removed = 0;
for (id, bounds) in found {
if bounds.is_none_or(|b| b.intersect(rect).is_zero_area()) {
@ -763,7 +900,7 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u
if !take_out(&mut without.layers, id, true) {
continue;
}
let d = view.difference(&without, rect);
let d = view.difference(&without, rect).any;
if d - with <= UNSEEN_MARGIN {
take_out(&mut doc.layers, id, false);
with = d;
@ -773,17 +910,30 @@ fn prune_unseen(frame: &Frame<'_>, view: &mut PageView, doc: &mut Document) -> u
removed
}
/// Do the layers' art and the page's own look alike? An error says they don't; `Ok` has the note
/// to give when they differ a little.
/// How far (points) the art the layers print may reach past a page that holds it all.
const PAST_THE_PAGE: f64 = 1.0;
/// Do the layers' art and the page's own look alike (where the page holds all the art that prints,
/// also round it)? An error says they don't; `Ok` has the note to give when they differ a little.
fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result<Option<String>, String> {
let diff = view.difference(layered, frame.rect);
if diff > MAX_DIFFERENCE {
return Err(format!("the art on them differs from the page's in {:.0}% of it", diff * 100.0));
let mut diff = view.difference(layered, frame.rect);
if frame.whole
&& let Some(art) = vectorcraft_render::encode::art_bounds(as_printed(layered).as_ref().unwrap_or(layered))
.filter(|a| !frame.rect.inflate(PAST_THE_PAGE, PAST_THE_PAGE).contains_rect(*a))
{
// The page and the art the layers print beyond it, each in its own document's place.
let all = frame.rect.union(art);
let (dx, dy) = (frame.page_rect.x0 - frame.rect.x0, frame.page_rect.y0 - frame.rect.y0);
let round = difference(frame.page, Rect::new(all.x0 + dx, all.y0 + dy, all.x1 + dx, all.y1 + dy), layered, all);
diff = Difference { any: diff.any.max(round.any), solid: diff.solid.max(round.solid) };
}
Ok((diff > NOTABLE_DIFFERENCE).then(|| {
if diff.any > MAX_DIFFERENCE || diff.solid > MAX_SOLID_DIFFERENCE {
return Err(format!("the art on them differs from the page's in {:.1}% of it", diff.any * 100.0));
}
Ok((diff.any > NOTABLE_DIFFERENCE).then(|| {
format!(
"the art on the layers differs from the file's own page in about {:.1}% of it (brush strokes, live effects and the like that the layers' data doesn't describe)",
diff * 100.0
diff.any * 100.0
)
}))
}
@ -794,7 +944,7 @@ fn compare(frame: &Frame<'_>, view: &mut PageView, layered: &Document) -> Result
/// has one that can't be used, `visible` with a warning that says why.
pub(super) fn layered(ps: &[u8], visible: Imported) -> Imported {
let Some(data) = ai::eps_data(ps) else { return visible };
let result = data.and_then(|data| build(&data, Some(&visible.document), Page::Art));
let result = data.and_then(|data| build(&data, Some(&visible.document), Page::Art, false));
match result {
Ok((document, mut warnings)) => {
for w in &visible.warnings {
@ -816,12 +966,14 @@ pub(super) fn layered(ps: &[u8], visible: Imported) -> Imported {
/// `AIPrivateData` streams) instead, as [`layered`] reads an EPS: with the layers and objects of the
/// file, its artboards, and the art that lies outside them, which its PDF part doesn't have.
/// `warnings` are the notes of reading the PDF part; the notes returned are those, and the layers'.
pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec<String>) -> (Document, Vec<String>) {
/// `outlined`: the PDF part's type was read as outlines (a file whose type shows then comes in as
/// its PDF part).
pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec<String>, outlined: bool) -> (Document, Vec<String>) {
let Ok(data) = ai::decode_private(private) else { return (visible, warnings) };
if !data.windows(15).any(|w| w == b"%AI5_BeginLayer") {
return (visible, warnings);
}
match build(&data, Some(&visible), Page::Artboard) {
match build(&data, Some(&visible), Page::Artboard, outlined) {
Ok((done, notes)) => {
let mut all = warnings;
all.extend(notes.into_iter().filter(|n| !all.contains(n)).collect::<Vec<_>>());
@ -839,7 +991,7 @@ pub fn layered_ai(private: &[u8], visible: Document, warnings: Vec<String>) -> (
/// alone (`private`, the joined `AIPrivateData` streams) → the document and the import's notes.
pub fn ai_alone(private: &[u8]) -> Result<(Document, Vec<String>), String> {
let data = ai::decode_private(private)?;
build(&data, None, Page::Artboard)
build(&data, None, Page::Artboard, false)
}
#[cfg(test)]

View File

@ -215,7 +215,7 @@ fn pdf_part(x: f64, y: f64) -> Document {
fn an_ai_file_gets_its_layers_and_the_art_outside_its_artboard() {
// A square on the artboard, and one above it (the artboard is y 0 to 100 here).
let art = native(&(layer("Jig", true, &square(10, 10)) + &layer("Parts", true, &square(30, 110)) + &layer("Old", false, &square(60, 60))));
let (d, warnings) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec!["a note".into()]);
let (d, warnings) = crate::layered_ai(&private(&art), pdf_part(10.0, 86.0), vec!["a note".into()], false);
assert_eq!(names(&d), ["Jig", "Parts", "Old"], "{warnings:?}");
assert_eq!(warnings, ["a note"], "nothing else to say");
let above = d.layers[1].children().unwrap()[0].visual_bounds().unwrap();
@ -227,12 +227,12 @@ fn an_ai_file_gets_its_layers_and_the_art_outside_its_artboard() {
fn an_ai_file_that_cant_be_read_through_its_editing_data_keeps_its_pdf_part() {
let pdf = pdf_part(10.0, 86.0);
// No editing data this reads.
let (d, w) = crate::layered_ai(b"nothing", pdf.clone(), vec![]);
let (d, w) = crate::layered_ai(b"nothing", pdf.clone(), vec![], false);
assert_eq!(d.layers.len(), pdf.layers.len());
assert!(w.is_empty());
// Editing data that isn't for this page.
let other = native(&layer("Jig", true, &square(10, 10))).replace("%AI3_Cropmarks: 0 0 100 100", "%AI3_Cropmarks: 0 0 50 50");
let (d, w) = crate::layered_ai(&private(&other), pdf.clone(), vec![]);
let (d, w) = crate::layered_ai(&private(&other), pdf.clone(), vec![], false);
assert_eq!(names(&d), names(&pdf));
assert!(w.iter().any(|w| w.contains("different page")), "{w:?}");
}
@ -280,7 +280,7 @@ fn custom_colours_open_paths_and_planar_group_marks_are_read() {
let body = "0.1 0.2 0.3 0.4 (Spot) 0 x\n0 0 0 1 (Edge) 0 X\n10 10 m\n14 10 L\n14 14 L\n10 14 L\nf\n\
0.8 0.1 0 0 62.7 -28 -42 (Blue) 0 2 Xx\n(Adobe Planar Group) 1 0 0 XP\n20 20 m\n24 20 L\n24 24 L\nH\nF";
let r = import(&older_eps(
"0 0 0 0 setcmykcolor 10 10 moveto 14 10 lineto 14 14 lineto 10 14 lineto closepath fill",
"0.1 0.2 0.3 0.4 setcmykcolor 10 10 moveto 14 10 lineto 14 14 lineto 10 14 lineto closepath fill 0.8 0.1 0 0 setcmykcolor 20 20 moveto 24 20 lineto 24 24 lineto closepath fill",
&native(&layer("Art", true, body)),
))
.unwrap();
@ -399,9 +399,9 @@ fn shown_type_keeps_the_pages_and_type_off_the_page_comes_from_the_text_document
fn a_text_object_written_as_comments_is_read_like_any_other() {
let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
let commented: String = text_object(0).lines().map(|l| format!("%_{l}\n")).collect();
let art = native_with_text(&layer("Spare", false, &(square(10, 10) + "\n" + &commented)), &doc);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &commented)), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts = text_of(&r.document.layers[0]);
let texts = text_of(&r.document.layers[1]);
assert_eq!(texts.len(), 1, "{:?}", r.warnings);
assert_eq!(texts[0].plain_text(), "Hi");
}
@ -453,9 +453,9 @@ fn a_commented_copy_of_a_story_that_has_a_plain_text_object_is_not_another_objec
let doc = text_document(&[("One\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0), ("Two\r", 0, (8300.0, 8180.0), (0.0, 0.0), 0.0)]);
let commented = |story| -> String { text_object(story).lines().map(|l| format!("%_{l}\n")).collect() };
let body = text_object(0) + &commented(0) + &commented(1);
let art = native_with_text(&layer("Spare", false, &body), &doc);
let art = native_with_text(&(layer("Back", true, &square(10, 10)) + &layer("Spare", false, &body)), &doc);
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
let texts: Vec<String> = text_of(&r.document.layers[0]).iter().map(|t| t.plain_text()).collect();
let texts: Vec<String> = text_of(&r.document.layers[1]).iter().map(|t| t.plain_text()).collect();
assert_eq!(texts, ["One", "Two"], "{:?}", r.warnings);
}
@ -542,3 +542,67 @@ fn an_ai_file_without_its_pdf_part_reads_its_layers_and_makes_its_type() {
assert!(!notes.iter().any(|n| n.contains("order the page paints")), "{notes:?}");
assert!(crate::ai_alone(b"%AI24_ZStandard_Data nothing").is_err());
}
#[test]
fn an_object_the_page_doesnt_draw_makes_the_file_come_in_as_its_page() {
// A 20-point square that the page doesn't draw: 4% of the page, and an object all the same.
let extra = "0 0 1 0 k\n50 50 m\n70 50 L\n70 70 L\n50 70 L\nf";
let art = native(&layer("Back", true, &(square(10, 10) + "\n" + extra)));
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert_eq!(names(&r.document), ["Layer 1"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("layers weren't read") && w.contains("differs from the page's")), "{:?}", r.warnings);
}
/// An EPS whose page is its art's box `[x0 y0 x1 y1]` (not its artboard, 0 0 100 100), drawing
/// `page`, with the editing copy of `layers`.
fn eps_of_art(art_box: [u32; 4], page: &str, layers: &str) -> Vec<u8> {
let [x0, y0, x1, y1] = art_box;
let native = native(layers).replace(
"%%BoundingBox: 0 0 100 100\n%%HiResBoundingBox: 0 0 100 100",
&format!("%%BoundingBox: {x0} {y0} {x1} {y1}\n%%HiResBoundingBox: {x0} {y0} {x1} {y1}"),
);
String::from_utf8(eps(page, &native))
.unwrap()
.replacen("%%BoundingBox: 0 0 100 100", &format!("%%BoundingBox: {x0} {y0} {x1} {y1}"), 1)
.into_bytes()
}
#[test]
fn art_the_layers_print_outside_an_eps_page_of_its_art_makes_it_come_in_as_its_page() {
// The page is the box of the art it prints, round the square at (10, 10).
let file = |far: &str| eps_of_art([10, 10, 14, 14], &page_square(10, 10), &(layer("Art", true, &square(10, 10)) + far));
// A square the layers print far from it: the page would have it.
let r = import(&file(&layer("Far", true, &square(80, 80)))).unwrap();
assert_eq!(names(&r.document), ["Layer 1"], "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("layers weren't read")), "{:?}", r.warnings);
// Hidden, or on a layer that doesn't print, the page doesn't have it.
let r = import(&file(&layer("Far", false, &square(80, 80)))).unwrap();
assert_eq!(names(&r.document), ["Art", "Far"], "{:?}", r.warnings);
let not_printed = format!("%AI5_BeginLayer\n1 1 1 0 0 0 1 0 79 128 255 0 50 0 Lb\n(Notes) Ln\n{}\nLB\n%AI5_EndLayer--\n", square(80, 80));
let r = import(&file(&not_printed)).unwrap();
assert_eq!(names(&r.document), ["Art", "Notes"], "{:?}", r.warnings);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
#[test]
fn an_eps_saved_as_its_artboard_keeps_the_art_outside_it() {
// The page is the artboard (0 0 100 100): the art beyond it is the pasteboard's.
let art = native(&(layer("Art", true, &square(10, 10)) + &layer("Scraps", true, &square(120, 10))));
let r = import(&eps(&page_square(10, 10), &art)).unwrap();
assert_eq!(names(&r.document), ["Art", "Scraps"], "{:?}", r.warnings);
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
}
#[test]
fn type_asked_for_as_outlines_leaves_a_file_whose_type_shows_as_its_pdf_part() {
let doc = text_document(&[("Hi\r", 0, (8200.0, 8180.0), (0.0, 0.0), 0.0)]);
// Type that shows: the PDF part's outlines are its type, which the text objects can't hold.
let shown = native_with_text(&layer("Art", true, &(square(10, 10) + "\n" + &text_object(0))), &doc);
let (d, w) = crate::layered_ai(&private(&shown), pdf_part(10.0, 86.0), vec![], true);
assert_eq!(names(&d), ["Layer 1"], "{w:?}");
assert!(w.iter().any(|w| w.contains("layers weren't read") && w.contains("outlines")), "{w:?}");
// Type only on a hidden layer: the layers come in.
let hidden = native_with_text(&(layer("Art", true, &square(10, 10)) + &layer("Notes", false, &text_object(0))), &doc);
let (d, w) = crate::layered_ai(&private(&hidden), pdf_part(10.0, 86.0), vec![], true);
assert_eq!(names(&d), ["Art", "Notes"], "{w:?}");
}

View File

@ -34,7 +34,7 @@ mod ps;
mod scene;
mod tiff;
pub use import::{Imported, ai_alone, family_style, import, is_loss, layered_ai};
pub use import::{Imported, ai_alone, family_style, import, import_with, is_loss, layered_ai};
pub use print::{PrintJob, PrintPage, print};
use vectorcraft_doc::Document;

View File

@ -86,7 +86,7 @@ impl RasterExportOptions {
self.ppi / 72.0
}
/// What the renderer draws for `format`: template layers left out, over the background
/// What the renderer draws for `format`: template layers and guides left out, over the background
/// (white for a JPEG or a flat PSD without one).
pub fn render_options(&self, format: RasterFormat) -> RenderOptions {
let flat = format == RasterFormat::Jpeg || (format == RasterFormat::Psd && !self.psd.layers);
@ -193,7 +193,7 @@ fn drawn_bounds(n: &Node) -> Option<Rect> {
}
match &n.kind {
NodeKind::Layer { template: true, .. } | NodeKind::Path { guide: true, .. } => None,
NodeKind::Layer { children, .. } | NodeKind::Group { children, clip: false } => {
NodeKind::Layer { children, clip: false, .. } | NodeKind::Group { children, clip: false } => {
children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, drawn_bounds(c)))
}
_ if fx::has_fx(n) => fx::visual_bounds(n),

View File

@ -189,3 +189,35 @@ fn art_bounds_cover_visible_art_only() {
let empty = Document::new(10.0, 10.0);
assert_eq!(art_bounds(&empty), None);
}
/// A black path round `r` in the first layer of `d`, made a guide when `guide`.
fn add_rect(d: &mut Document, r: Rect, guide: bool) {
let id = d.alloc_id();
let mut n = Node::path(id, shapes::rectangle(r), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0));
if let NodeKind::Path { guide: g, .. } = &mut n.kind {
*g = guide;
}
let l = d.layers[0].id;
d.insert(Some(l), 0, n).unwrap();
}
#[test]
fn guides_dont_count_in_the_arts_bounds() {
let mut d = circle_doc();
add_rect(&mut d, Rect::new(0.0, 15.0, 400.0, 15.0), true);
let b = art_bounds(&d).unwrap();
assert!((b.x0 - 5.3).abs() < 1e-6 && (b.x1 - 31.1).abs() < 1e-6, "the guide doesn't count: {b:?}");
}
#[test]
fn art_bounds_end_at_a_clipping_layers_clip() {
let mut d = Document::new(40.0, 30.0);
// The layer clips its art to its first object (added last): what lies beyond isn't drawn.
add_rect(&mut d, Rect::new(-100.0, -100.0, 200.0, 200.0), false);
add_rect(&mut d, Rect::new(2.0, 3.0, 20.0, 10.0), false);
let layer = std::sync::Arc::make_mut(&mut d.layers[0]);
if let NodeKind::Layer { clip, .. } = &mut layer.kind {
*clip = true;
}
assert_eq!(art_bounds(&d), Some(Rect::new(2.0, 3.0, 20.0, 10.0)));
}

View File

@ -582,7 +582,7 @@ impl Renderer {
}
/// Render one artboard (or any document rect) at `scale` pixels per point, transparent or on white,
/// as exported: template layers are left out.
/// as exported: template layers and guides are left out.
pub fn render_region(&mut self, doc: &Document, region: Rect, scale: f64, white: bool) -> Rendered {
let opts = RenderOptions { background: white.then_some([255, 255, 255, 255]), skip_templates: true, ..Default::default() };
self.render_region_with(doc, region, scale, &opts)

View File

@ -3170,6 +3170,7 @@ axis Both Ambos
@msg its editing data is for a different page sus datos de edición son de otra página
@msg its layers use {_1}, which aren't read yet sus capas usan {_1}, que aún no se leen
@msg its page has text, and its layers have no text objects to put it in su página tiene texto y sus capas no tienen objetos de texto donde ponerlo
@msg its type is to come in as outlines, which only its page has su texto debe llegar como contornos, y solo su página los tiene
@msg the art on them differs from the page's in {_1}% of it el arte de las capas difiere del de la página en el {_1} % de su superficie
@msg `to` must be "corner" or "smooth" `to` debe ser "corner" o "smooth"
@msg BMP files are RGB or grayscale: colorModel rgb or gray los archivos BMP son RGB o en escala de grises: colorModel rgb o gray

Can't render this file because it contains an unexpected character in line 2 and column 73.

View File

@ -3167,6 +3167,7 @@ axis Both Les deux
@msg its editing data is for a different page ses données de modification concernent une autre page
@msg its layers use {_1}, which aren't read yet ses calques utilisent {_1}, qui ne sont pas encore lus
@msg its page has text, and its layers have no text objects to put it in sa page contient du texte, et ses calques n’ont aucun objet texte où le mettre
@msg its type is to come in as outlines, which only its page has son texte doit être importé sous forme de contours vectorisés, que seule sa page contient
@msg the art on them differs from the page's in {_1}% of it le dessin des calques diffère de celui de la page sur {_1} % de sa surface
@msg `to` must be "corner" or "smooth" `to` doit être "corner" ou "smooth"
@msg BMP files are RGB or grayscale: colorModel rgb or gray Les fichiers BMP sont en RVB ou en niveaux de gris : colorModel rgb ou gray

Can't render this file because it contains an unexpected character in line 2 and column 73.

View File

@ -3170,6 +3170,7 @@ axis Both Entrambi
@msg its editing data is for a different page i suoi dati di modifica sono di un'altra pagina
@msg its layers use {_1}, which aren't read yet i suoi livelli usano {_1}, che non vengono ancora letti
@msg its page has text, and its layers have no text objects to put it in la sua pagina ha del testo e i suoi livelli non hanno oggetti di testo in cui metterlo
@msg its type is to come in as outlines, which only its page has il suo testo deve arrivare come contorni, che ha solo la sua pagina
@msg the art on them differs from the page's in {_1}% of it l'illustrazione dei livelli differisce da quella della pagina per il {_1}% della sua superficie
@msg `to` must be "corner" or "smooth" `to` deve essere "corner" o "smooth"
@msg BMP files are RGB or grayscale: colorModel rgb or gray I file BMP sono RGB o in scala di grigi: colorModel rgb o gray

Can't render this file because it contains an unexpected character in line 2 and column 73.

View File

@ -3177,6 +3177,7 @@ theme Appearance 外観
@msg it has more than one artboard アートボードが複数あります
@msg its editing data has no layers 編集データにレイヤーがありません
@msg its editing data is damaged 編集データが破損しています
@msg its type is to come in as outlines, which only its page has 文字をアウトラインとして読み込む設定ですが、アウトラインはページにしかありません
@msg {_1} files {_1} 個のファイル
@msg A browser with WebGPU or WebGL2 is required. WebGPU または WebGL2 に対応したブラウザーが必要です。
@msg Loading VectorCraft… VectorCraft を読み込んでいます…

Can't render this file because it contains an unexpected character in line 2 and column 73.

View File

@ -3166,6 +3166,7 @@ axis Both Оба
@msg its editing data is for a different page его данные для редактирования относятся к другой странице
@msg its layers use {_1}, which aren't read yet его слои используют {_1}, что пока не читается
@msg its page has text, and its layers have no text objects to put it in на его странице есть текст, а на слоях нет текстовых объектов, куда его поместить
@msg its type is to come in as outlines, which only its page has его текст должен прийти в виде контуров, а они есть только на его странице
@msg the art on them differs from the page's in {_1}% of it изображение на слоях отличается от изображения на странице на {_1} % площади
@msg `to` must be "corner" or "smooth" `to` должно быть "corner" или "smooth"
@msg BMP files are RGB or grayscale: colorModel rgb or gray файлы BMP бывают RGB или в оттенках серого: colorModel rgb или gray

Can't render this file because it contains an unexpected character in line 2 and column 73.

View File

@ -3153,6 +3153,7 @@ axis Both Обидві
@msg its editing data is for a different page його дані для редагування відносяться до іншої сторінки
@msg its layers use {_1}, which aren't read yet його шари використовують {_1}, що поки не читається
@msg its page has text, and its layers have no text objects to put it in на його сторінці є текст, а на шарах немає текстових об’єктів, куди його помістити
@msg its type is to come in as outlines, which only its page has його текст має прийти у вигляді контурів, а вони є лише на його сторінці
@msg the art on them differs from the page's in {_1}% of it зображення на шарах відрізняється від зображення на сторінці на {_1} % площі
@msg `to` must be "corner" or "smooth" `to` має бути "corner" або "smooth"
@msg BMP files are RGB or grayscale: colorModel rgb or gray Файли BMP бувають RGB або у відтінках сірого: colorModel rgb або gray

Can't render this file because it has a wrong number of fields in line 14.

View File

@ -416,7 +416,19 @@ strokes, effects or a brush comes in as its drawn look (a group named after it).
text object's place; hidden point type is made from the file's text document. A file whose editing data has symbols,
pattern fills, placed files or anything else the reader doesn't read on a layer that shows, or whose layers look
different from its page, opens as before: an EPS as its printed page, a `.ai` file from its PDF content (where plain
groups open ungrouped), with a warning saying why.
groups open ungrouped), with a warning saying why. Layers look different when they draw an object the page doesn't (or
miss one it draws), and, for an EPS whose page is the box of its art, when they print art outside it. With
`textAs: "outlines"` a `.ai` file whose type shows opens from its PDF content, which has the type's outlines.
The document then has what the file's page doesn't print: hidden objects and layers, layers that don't print, guides and
the art outside the artboards, as the app that wrote the file shows them. Exports and `artboard.fitToArt` leave out the
hidden art, the guides and template layers; an EPS's artboard is the file's artboard, not the page's bounding box. A
print pipeline that wants only what the page prints opens the file with `editingData: false` (default `true`):
an EPS as its page, a `.ai` file from its PDF content (a `.ai` saved without PDF compatibility then can't be opened).
```json
{"name":"run_command","arguments":{"command":"document.open","params":{"path":"/tmp/label.eps","editingData":false}}}
```
Opening a PDF (or `.ai`) imports every page as an artboard and layer; `document.open` takes `pages` ("2-3, 5", 1-based),
`cropTo` (`bounding` (the art's bounds), `art`, `crop` (default), `trim`, `bleed`, `media`: the box each artboard gets)