diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index bed5bef361..0b2ceef183 100644 --- a/crates/cad/src/import.rs +++ b/crates/cad/src/import.rs @@ -7,7 +7,8 @@ //! becomes a layer (hidden, frozen, locked and non-plotting layers keep that), or all art goes on //! one. Lines, polylines with arc segments, circles, arcs, ellipses, splines (NURBS), solid //! hatches, solids and regions become paths; text and multiline text point type; named blocks symbols -//! (anonymous ones, such as dimensions, groups of their art). Colours (indexed and true colour), +//! (anonymous ones, such as dimensions, groups of their art); raster images linked images of the +//! files they name, clipped by their clip boundaries. Colours (indexed and true colour), //! lineweights, linetypes and transparency come through layers and blocks as CAD apps resolve //! them. What can't come in is listed in the warnings. //! @@ -240,4 +241,6 @@ mod tests; #[cfg(test)] mod tests_dwg; #[cfg(test)] +mod tests_image; +#[cfg(test)] mod tests_region; diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 0b3532ca87..5d1eec93e7 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -9,11 +9,14 @@ use std::sync::Arc; use kurbo::BezPath; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Dash, Document, LAYER_COLORS, LayerColor, LineCap, Node, NodeKind, Symbol, TextObject}; +use vectorcraft_doc::{ + Appearance, AppearanceItem, CharStyle, Dash, Document, ImageBlob, ImageObject, LAYER_COLORS, LayerColor, LineCap, LinkInfo, Node, NodeKind, + Symbol, TextObject, +}; use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect}; use super::ImportOptions; -use super::entity::{Alpha, Col, Converter, Geom, InsertItem, Item, Lw, Props, Span, TextItem}; +use super::entity::{Alpha, Col, Converter, Geom, ImageItem, InsertItem, Item, Lw, Props, Span, TextItem}; use super::reader::{Drawing, LayoutDef}; use crate::{CAP_HEIGHT, MAX_NEST}; @@ -22,7 +25,7 @@ const PT_PER_MM: f64 = 72.0 / 25.4; /// The stroke weight of lineweight 0 (CAD apps draw it one device pixel wide), in points. const THINNEST: f64 = 0.25; /// The most objects an import makes. -const MAX_NODES: usize = 2_000_000; +const MAX_NODES: usize = if cfg!(test) { 100_000 } else { 2_000_000 }; /// The most block work an import does, whatever it produces: one per insert copy drawn, and one /// per item of the block looked at for it (art on hidden layers too). const MAX_VISITS: usize = if cfg!(test) { 1_000_000 } else { 20_000_000 }; @@ -38,6 +41,9 @@ const MAX_TEXT_BYTES: usize = if cfg!(test) { 64 << 10 } else { 64 << 20 }; const MAX_FAMILY_BYTES: usize = 256; /// How far from the origin art may lie (points): the canvas. pub(crate) const MAX_EXTENT: f64 = 4.0e6; +/// How far from a symbol's origin its image clip points may lie (points): as far as an insert at +/// the smallest scale it accepts (1e-12) still brings back onto the canvas. +const MAX_SYMBOL_EXTENT: f64 = MAX_EXTENT * 1e12; const NESTED: &str = "blocks nested more than 8 deep, or inside themselves, are left out"; const XREFS: &str = "blocks referencing other drawings (external references) are left out"; @@ -46,6 +52,14 @@ const TOO_MANY_POINTS: &str = "the drawing has more than 4,000,000 path points: const TOO_MUCH_BLOCK_WORK: &str = "the drawing's blocks take too much work to place: the rest are left out"; const TOO_MANY_DASHES: &str = "the drawing has more dashed lines than can be kept: the rest are drawn solid"; const TOO_MUCH_TEXT: &str = "the drawing has more than 64 MB of text and block names: the rest are left out"; +const NO_IMAGE_FILE: &str = "images that name no image file are left out"; +const FAR_CLIPS: &str = "images whose clip boundaries reach out of range are left out"; +const IMAGE_SIZE: &str = "images with no size in pixels, or more than 1,048,576 pixels a side, are left out"; +/// The most pixels an image may have a side. +const MAX_IMAGE_SIDE: f64 = 1_048_576.0; +/// The key of the image data of the images showing the file at a path: the placeholder, until +/// the file is read. +const IMAGE_KEY: &str = "dxf-image-"; /// What a block's art takes from the insert that places it: its colour, lineweight, linetype /// and opacity where the art says "by block", and its layer for art on layer 0. @@ -58,6 +72,35 @@ struct Inherit { layer: Option, } +/// Objects, path elements, dash lengths and text bytes taken from the import's limits. +#[derive(Clone, Copy, Debug, Default)] +struct Cost { + nodes: usize, + elements: usize, + dash_values: usize, + text_bytes: usize, +} + +impl Cost { + fn minus(self, o: Cost) -> Cost { + Cost { + nodes: self.nodes.saturating_sub(o.nodes), + elements: self.elements.saturating_sub(o.elements), + dash_values: self.dash_values.saturating_sub(o.dash_values), + text_bytes: self.text_bytes.saturating_sub(o.text_bytes), + } + } + + fn plus(self, o: Cost) -> Cost { + Cost { + nodes: self.nodes.saturating_add(o.nodes), + elements: self.elements.saturating_add(o.elements), + dash_values: self.dash_values.saturating_add(o.dash_values), + text_bytes: self.text_bytes.saturating_add(o.text_bytes), + } + } +} + pub(crate) struct Build<'d, 'a> { d: &'d Drawing<'a>, o: &'d ImportOptions, @@ -74,6 +117,21 @@ pub(crate) struct Build<'d, 'a> { next_suffix: HashMap, /// Blocks being drawn, outermost first. stack: Vec, + /// How many symbols' art is being drawn: above 0, art is in a symbol's own space. + in_symbol: u32, + /// The box of the image clip points in the symbol being drawn, in its own space, and of each + /// symbol made (none: its art has no clips). + clip_reach: Option, + symbol_reach: HashMap, + /// What each symbol's own art took from the limits (not the symbols made while drawing it), + /// how many instances place each symbol, and what the symbols made inside the one being + /// drawn took. + symbol_cost: HashMap, + uses: HashMap, + nested: Cost, + /// Each symbol's place in the document's symbols, and the symbols whose art was taken out. + symbol_slot: HashMap, + empty: HashSet, /// Document space per drawing unit, and its symbols' (no translation). map: Affine, symbol_map: Affine, @@ -137,6 +195,14 @@ impl<'d, 'a> Build<'d, 'a> { symbol_names: HashSet::new(), next_suffix: HashMap::new(), stack: vec![], + in_symbol: 0, + clip_reach: None, + symbol_reach: HashMap::new(), + symbol_cost: HashMap::new(), + uses: HashMap::new(), + symbol_slot: HashMap::new(), + empty: HashSet::new(), + nested: Cost::default(), map: Affine::IDENTITY, symbol_map: Affine::IDENTITY, lw_scale: 1.0, @@ -169,6 +235,72 @@ impl<'d, 'a> Build<'d, 'a> { } } + /// What the import has taken from its limits so far. + fn cost(&self) -> Cost { + Cost { nodes: self.nodes, elements: self.elements, dash_values: self.dash_values, text_bytes: self.text_bytes } + } + + fn set_cost(&mut self, c: Cost) { + self.nodes = c.nodes; + self.elements = c.elements; + self.dash_values = c.dash_values; + self.text_bytes = c.text_bytes; + } + + /// Take symbol `name`'s art out when no instance places it, giving back its share of the limits + /// and its art's instances of other symbols (and in turn those that no instance places any + /// more); the art, when it was taken. The symbol stays empty until [`Self::restore`] puts the + /// art back or [`Self::symbol`] draws it again, and is dropped at the end if still empty. + fn take_unused(&mut self, name: &str) -> Option> { + let first = self.take_art(name)?; + // A worklist, not recursion: chains of symbols can be long. + let mut todo = placed_symbols(&first); + while let Some(s) = todo.pop() { + if let Some(n) = self.uses.get_mut(&s) { + *n = n.saturating_sub(1); + } + if let Some(art) = self.take_art(&s) { + todo.extend(placed_symbols(&art)); + } + } + Some(first) + } + + /// Symbol `name`'s art, taken out with its share of the limits when no instance places it. + fn take_art(&mut self, name: &str) -> Option> { + if self.uses.get(name).is_some_and(|n| *n > 0) || self.empty.contains(name) { + return None; + } + let i = *self.symbol_slot.get(name)?; + let id = self.doc.alloc_id(); + let art = std::mem::replace(&mut self.doc.symbols.get_mut(i)?.art, Arc::new(Node::group(id, vec![]))); + self.set_cost(self.cost().minus(self.symbol_cost.get(name).copied().unwrap_or_default())); + self.empty.insert(name.to_string()); + Some(art) + } + + /// Put `art`, taken from symbol `name` by [`Self::take_unused`], back, charging its share of + /// the limits again; false (nothing changed) when that share no longer fits. + fn restore(&mut self, name: &str, art: Arc) -> bool { + let t = self.cost().plus(self.symbol_cost.get(name).copied().unwrap_or_default()); + let inner = placed_symbols(&art); + // Its instances of symbols that are empty now need those drawn again. + let fits = t.nodes < MAX_NODES && t.elements <= MAX_ELEMENTS && t.dash_values <= MAX_DASH_VALUES && t.text_bytes <= MAX_TEXT_BYTES; + if !fits || inner.iter().any(|s| self.empty.contains(s)) { + return false; + } + let Some(slot) = self.symbol_slot.get(name).and_then(|i| self.doc.symbols.get_mut(*i)) else { + return false; + }; + slot.art = art; + self.set_cost(t); + self.empty.remove(name); + for s in inner { + *self.uses.entry(s).or_default() += 1; + } + true + } + /// Import `layout`; `natural` and `ratio` are points per drawing unit in the drawing's own /// unit and at the scale asked for (fitting computes its own). pub fn run(mut self, layout: &LayoutDef, natural: f64, ratio: f64) -> Result<(Document, Vec), String> { @@ -183,6 +315,7 @@ impl<'d, 'a> Build<'d, 'a> { if !layers.is_empty() { doc.layers = layers; } + drop_unplaced_symbols(&mut doc); if let Some(a) = doc.artboards.first_mut() { a.rect = Rect::from_origin_size(Point::ZERO, size); } @@ -314,6 +447,14 @@ impl<'d, 'a> Build<'d, 'a> { let attribs: Vec> = ins.attribs.iter().map(|a| self.item_bounds(a, depth)).collect(); cells.map(Some).chain(attribs).fold(None, vectorcraft_geom::union_opt) } + Geom::Image(im) => { + self.image_file(im)?; + let (w, h) = self.image_size(im)?; + let place = im.placement(h); + let whole = place.transform_rect_bbox(Rect::new(0.0, 0.0, w, h)); + let clip = im.clip.as_ref().and_then(|c| c.iter().map(|p| place * *p).map(|p| Rect::from_points(p, p)).reduce(|a, b| a.union(b))); + Some(clip.map_or(whole, |c| c.intersect(whole))) + } } .filter(|r| [r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) } @@ -482,6 +623,7 @@ impl<'d, 'a> Build<'d, 'a> { Geom::Path { bp, fill, width } => self.path(bp, *fill, *width, &it.props, map, inh)?, Geom::Text(t) => self.text(t, &it.props, map, inh)?, Geom::Insert(ins) => return self.insert(ins, &it.props, map, inh, depth), + Geom::Image(im) => self.image(im, map)?, }; node.opacity = self.opacity(&it.props, inh); self.nodes += 1; @@ -590,6 +732,92 @@ impl<'d, 'a> Build<'d, 'a> { Some(Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj)))) } + /// The non-empty, trimmed file path that image `im`'s IMAGEDEF names. + fn image_file(&self, im: &ImageItem) -> Option { + im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty()) + } + + /// The size in pixels of image `im`: its own, else its file's as its IMAGEDEF gives it. + fn image_size(&self, im: &ImageItem) -> Option<(f64, f64)> { + let def = im.def.and_then(|h| self.d.images.get(&h)).map_or([0.0; 2], |f| f.size); + let size = if im.size.iter().all(|v| *v >= 1.0) { im.size } else { def }; + let [w, h] = size.map(f64::round); + [w, h].iter().all(|v| (1.0..=MAX_IMAGE_SIDE).contains(v)).then_some((w, h)) + } + + /// A raster image, linked to the file its IMAGEDEF names (the path as the drawing stores it, + /// found from the drawing's folder when the document opens): until the file is read it shows + /// a placeholder over its pixels. A clip boundary makes it a clip group. + fn image(&mut self, im: &ImageItem, map: Affine) -> Option { + let Some(path) = self.image_file(im) else { + self.warn(NO_IMAGE_FILE); + return None; + }; + let Some((w, h)) = self.image_size(im) else { + self.warn(IMAGE_SIZE); + return None; + }; + let xf = map * im.placement(h); + if !(xf.as_coeffs().iter().all(|v| v.is_finite()) && xf.determinant() != 0.0) { + return None; + } + // The clip boundary, unless it shows the whole image. Its path and the image are objects of + // their own (`item` counts the group), and its points and the close are path elements: both + // are checked against the limits before the points are read. + let clip = im.clip.as_ref().filter(|c| !covers(c, w, h)); + let elements = clip.map_or(0, |c| c.len().saturating_add(1)); + if clip.is_some() && self.nodes.saturating_add(2) >= MAX_NODES { + self.warn(TOO_MANY); + return None; + } + if self.elements.saturating_add(elements) > MAX_ELEMENTS { + self.warn(TOO_MANY_POINTS); + return None; + } + // In document space, or in a symbol's own space, where each instance places it. + let clip: Option> = clip.map(|c| c.iter().map(|p| xf * *p).collect()); + let local = self.in_symbol > 0; + let limit = if local { MAX_SYMBOL_EXTENT } else { MAX_EXTENT }; + let fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= limit && p.y.abs() <= limit; + if clip.as_ref().is_some_and(|c| !c.iter().all(fits)) { + self.warn(FAR_CLIPS); + return None; + } + // Each image keeps its own copy of the path. + if !self.charge_text(path.len()) { + return None; + } + let key = format!("{IMAGE_KEY}{}", vectorcraft_doc::links::hash_bytes(path.as_bytes())); + if !self.doc.images.contains_key(&key) { + let bytes = Arc::new(vectorcraft_doc::links::missing_placeholder()?); + let blob = ImageBlob { + mime: vectorcraft_doc::links::PROXY_MIME.into(), + bytes: bytes.clone(), + proxy: Some(bytes), + file_font: Default::default(), + }; + self.doc.images.insert(key.clone(), blob); + } + let (w_px, h_px) = (w as u32, h as u32); + let image = ImageObject { key, width: w_px, height: h_px, xf, link: Some(LinkInfo::new(path)), placement: Default::default(), pixels: None }; + let image = Node::new(self.doc.alloc_id(), NodeKind::Image(Box::new(image))); + let Some(clip) = clip else { return Some(image) }; + // A symbol's clips are checked where each of its instances places them. + if local && let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) { + self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); + } + self.nodes += 2; + self.elements += elements; + let mut bp = BezPath::new(); + for (i, p) in clip.iter().enumerate() { + if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) } + } + bp.close_path(); + let path = PathData::from_bezpath(&bp); + let clip = Node::new(self.doc.alloc_id(), NodeKind::Path { path, rule: FillRule::NonZero, live: None, clipping: true, guide: false }); + Some(Node::new(self.doc.alloc_id(), NodeKind::Group { children: vec![Arc::new(clip), Arc::new(image)], clip: true })) + } + /// An insert: a symbol instance per copy (anonymous blocks: a group of their art), grouped /// with its attributes. fn insert(&mut self, ins: &InsertItem, p: &Props, map: Affine, inh: &Inherit, depth: u32) -> Option { @@ -597,11 +825,53 @@ impl<'d, 'a> Build<'d, 'a> { let base = self.d.blocks.get(&ins.block).map_or(Point::ZERO, |b| b.base); let unbase = Affine::translate(-base.to_vec2()); let anonymous = ins.block.starts_with('*'); - let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth) }; + // An empty symbol is drawn again only for a cell that places an instance of it. + let symbol = if anonymous { None } else { self.symbol(&ins.block, &child, depth, false) }; + // The symbol's art when this insert took it out. + let mut taken = None; let mut parts = vec![]; for cell in &ins.cells { let node = match &symbol { Some(name) => { + let xf = map * *cell * self.symbol_map.inverse(); + // Its image clips where this instance places them: inside another symbol, their + // box joins that symbol's; else, when it may leave the canvas, this placement + // draws the block's art, which checks each clip where it lands. + let reach_of = |b: &Self| b.symbol_reach.get(name).map(|r| placed_reach(xf, *r)); + let leaves = + |r: Option| r.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT)); + let mut reach = reach_of(self); + // An empty symbol is drawn again (or its taken art put back) unless this placement + // draws the art anyway; the art drawn again may reach further. + if self.empty.contains(name) && (self.in_symbol > 0 || !leaves(reach)) { + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + let back = taken.take().is_some_and(|art| self.restore(name, art)); + if !back && self.symbol(&ins.block, &child, depth, true).is_none() { + continue; + } + reach = reach_of(self); + } + // Joins the enclosing symbol's box once the instance is kept. + let inside = reach.filter(|_| self.in_symbol > 0); + if inside.is_none() && leaves(reach) { + // This placement draws the art instead of the symbol. The art of a symbol + // no instance places yet is taken out, so that it isn't kept and charged + // as well; an instance in a later cell puts it back. + if taken.is_none() { + taken = self.take_unused(name); + } + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth)); + continue; + } + // Checked here, after the art drawn in its place: that art gets back the + // share of an unused symbol. if self.nodes >= MAX_NODES { self.warn(TOO_MANY); break; @@ -609,7 +879,10 @@ impl<'d, 'a> Build<'d, 'a> { if !self.charge_text(name.len()) { break; } - let xf = map * *cell * self.symbol_map.inverse(); + if let Some(b) = inside { + self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); + } + *self.uses.entry(name.clone()).or_default() += 1; self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) } @@ -664,30 +937,124 @@ impl<'d, 'a> Build<'d, 'a> { } } - /// The symbol for block `name` placed with `inh` (made once per look). - fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32) -> Option { + /// The symbol for block `name` placed with `inh` (made once per look). One whose art was + /// taken out is drawn again when `draw` is set, and else returned empty. + fn symbol(&mut self, name: &str, inh: &Inherit, depth: u32, draw: bool) -> Option { let inh = if self.is_sensitive(name, depth) { inh.clone() } else { Inherit::default() }; let key = (name.to_string(), inh); if let Some(s) = self.symbols.get(&key) { - return s.clone(); - } - let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); - let map = self.symbol_map * Affine::translate(-base.to_vec2()); - let art = self.art(name, map, &key.1, depth); - let made = art.and_then(|art| { - let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); - // The symbol keeps its name: text, as its instances' copies of it are. - if !self.charge_text(label.len()) { - return None; + let s = s.clone()?; + if !draw || !self.empty.contains(&s) { + return Some(s); } + let (art, reach, cost) = self.symbol_art(name, &key.1, depth); + let slot = self.symbol_slot.get(&s).and_then(|i| self.doc.symbols.get_mut(*i)); + return match (art, slot) { + (Some(art), Some(slot)) => { + slot.art = Arc::new(art); + self.symbol_cost.insert(s.clone(), cost); + match reach { + Some(b) => self.symbol_reach.insert(s.clone(), b), + None => self.symbol_reach.remove(&s), + }; + self.empty.remove(&s); + Some(s) + } + // Nothing of it fits now: what it took goes back, and it stays empty. + _ => { + self.set_cost(self.cost().minus(cost)); + self.nested = self.nested.minus(cost); + None + } + }; + } + let (art, reach, cost) = self.symbol_art(name, &key.1, depth); + let made = art.map(|art| { + let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()); let symbol = unique(label, &mut self.next_suffix, &self.symbol_names); self.symbol_names.insert(symbol.clone()); + if let Some(b) = reach { + self.symbol_reach.insert(symbol.clone(), b); + } + self.symbol_slot.insert(symbol.clone(), self.doc.symbols.len()); + self.symbol_cost.insert(symbol.clone(), cost); self.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); - Some(symbol) + symbol }); self.symbols.insert(key, made.clone()); made } + + /// The art of the symbol for block `name` placed with `inh`, the box of its image clips, and + /// what it took from the limits itself (not the symbols made while drawing it, which other + /// instances may use). + fn symbol_art(&mut self, name: &str, inh: &Inherit, depth: u32) -> (Option, Option, Cost) { + let base = self.d.blocks.get(name).map_or(Point::ZERO, |b| b.base); + let map = self.symbol_map * Affine::translate(-base.to_vec2()); + let outer = self.clip_reach.take(); + let before = self.cost(); + let outer_nested = std::mem::take(&mut self.nested); + self.in_symbol += 1; + let art = self.art(name, map, inh, depth); + self.in_symbol -= 1; + let reach = std::mem::replace(&mut self.clip_reach, outer); + let label = self.d.blocks.get(name).map_or(name, |b| b.name.as_str()).len(); + // The symbol keeps its name: text, as its instances' copies of it are. + let art = art.filter(|_| self.charge_text(label)); + let total = self.cost().minus(before); + let own = total.minus(self.nested); + self.nested = outer_nested.plus(total); + (art, reach, own) + } +} + +/// The box of `r` placed by `xf`. A box that is not finite, or whose placed corners are not (an +/// overflow, which a union or a bounding box would drop as NaN), is the whole plane, so every +/// placement of it is out of range. +pub(crate) fn placed_reach(xf: Affine, r: Rect) -> Rect { + let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)].map(|p| xf * p); + match corners.iter().all(|p| p.x.is_finite() && p.y.is_finite()) { + true => corners.iter().fold(Rect::from_points(corners[0], corners[0]), |b, p| b.union_pt(*p)), + false => Rect::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::INFINITY), + } +} + +/// The symbol of each instance in `art`, once per instance. +fn placed_symbols(art: &Node) -> Vec { + let mut out = vec![]; + art.walk(&mut |n: &Node| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind { + out.push(symbol.clone()); + } + }); + out +} + +/// Every symbol of `doc` that no instance on its layers places, directly or through other +/// symbols, removed. +fn drop_unplaced_symbols(doc: &mut Document) { + let index: HashMap<&str, usize> = doc.symbols.iter().enumerate().map(|(i, s)| (s.name.as_str(), i)).collect(); + let mut placed = vec![false; doc.symbols.len()]; + let mut todo: Vec = vec![]; + // Each symbol is queued once, however many instances place it. + let note = |n: &Node, placed: &mut Vec, todo: &mut Vec| { + if let NodeKind::SymbolInstance { symbol, .. } = &n.kind + && let Some(&i) = index.get(symbol.as_str()) + && let Some(seen) = placed.get_mut(i) + && !*seen + { + *seen = true; + todo.push(i); + } + }; + doc.walk(|n| note(n, &mut placed, &mut todo)); + while let Some(i) = todo.pop() { + if let Some(s) = doc.symbols.get(i) { + s.art.walk(&mut |n: &Node| note(n, &mut placed, &mut todo)); + } + } + let mut keep = placed.into_iter(); + doc.symbols.retain(|_| keep.next().unwrap_or(false)); } /// Fit text stretched or squeezed across, aligned text scaled as a whole, to run its span @@ -704,6 +1071,22 @@ fn fill_span(obj: &mut TextObject, span: Span, s: f64) { } } +/// Does clip boundary `clip` (pixel space) show the whole `w` × `h` image: is it a rectangle +/// square to the image that holds it? +fn covers(clip: &[Point], w: f64, h: f64) -> bool { + if clip.len() != 4 || clip.iter().enumerate().any(|(i, p)| clip[..i].contains(p)) { + return false; + } + let Some(b) = clip.iter().map(|p| Rect::from_points(*p, *p)).reduce(|a, b| a.union(b)) else { return false }; + let corner = |p: &Point| (p.x == b.x0 || p.x == b.x1) && (p.y == b.y0 || p.y == b.y1); + // Each point a distinct corner, and each edge along one side: the four corners in order around. + let side = |i: usize| { + let (p, q) = (clip[i], clip[(i + 1) % clip.len()]); + (p.x == q.x) != (p.y == q.y) + }; + clip.len() == 4 && clip.iter().all(corner) && (0..4).all(side) && b.x0 <= 0.0 && b.y0 <= 0.0 && b.x1 >= w && b.y1 >= h +} + fn rgb_color([r, g, b]: [u8; 3]) -> Color { Color::rgb8(r, g, b) } diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index acca831206..1cb213b4ad 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -148,6 +148,31 @@ pub(crate) struct InsertItem { pub attribs: Vec, } +/// A raster image: the file its IMAGEDEF names, shown on a parallelogram. +#[derive(Clone, Debug)] +pub(crate) struct ImageItem { + /// The handle of its IMAGEDEF. + pub def: Option, + /// The lower-left corner, and one pixel along the width and up the height (world + /// coordinates, drawing units). + pub insert: Point, + pub u: Vec2, + pub v: Vec2, + /// Its size in pixels (0: its IMAGEDEF's). + pub size: [f64; 2], + /// The clip boundary in pixel space ([`ImageItem::placement`]); `None`: the whole image. + pub clip: Option>, +} + +impl ImageItem { + /// Pixel space (the top-left corner at the origin, x right, y down, one unit a pixel) to world + /// coordinates, for an image `height` pixels high. + pub fn placement(&self, height: f64) -> Affine { + let top = self.insert + self.v * height; + Affine::new([self.u.x, self.u.y, -self.v.x, -self.v.y, top.x, top.y]) + } +} + #[derive(Clone, Debug)] pub(crate) enum Geom { /// A path in world coordinates; `fill`: a filled area (hatch, solid), else a line of @@ -159,6 +184,7 @@ pub(crate) enum Geom { }, Text(TextItem), Insert(InsertItem), + Image(ImageItem), } /// An entity as art: its geometry and its properties. @@ -186,6 +212,10 @@ const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertic const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each"; const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all"; const FAR_AWAY: &str = "entities with coordinates out of range are left out"; +const FLAT_IMAGES: &str = "images with no width or height are left out"; +const IMAGE_ADJUSTMENTS: &str = "the brightness, contrast and fade of images are left out"; +const OPAQUE_IMAGES: &str = "images set to show opaque keep their file's transparency"; +const INVERTED_CLIPS: &str = "inverted image clips are left out: those images show whole"; const REGION_CURVES: &str = "region edges of some curve types come in as straight lines"; const REGION_BROKEN: &str = "regions whose outlines break off are closed with straight lines"; const REGION_AMBIGUOUS: &str = "region edges on curves that cross themselves may come in along the wrong part of the curve"; @@ -267,11 +297,39 @@ impl Converter { model::EntityKind::Dimension(d) => { Some(Geom::Insert(InsertItem { block: d.block.as_ref()?.to_uppercase(), cells: vec![Affine::IDENTITY], attribs: vec![] })) } + // Group 70 without its Show Image bit: a hidden image (an IMAGE without group 70 shows). + model::EntityKind::Image(_) if g.i(70).is_some_and(|flags| flags & 1 == 0) => None, + model::EntityKind::Image(im) => self.image(im, g.i(70).is_some()), _ if e.kind == "REGION" => self.region(e), _ => None, } } + /// An IMAGE (its points are in world coordinates). + fn image(&mut self, im: &model::Image, has_display: bool) -> Option { + let (u, v) = (point(im.u).to_vec2(), point(im.v).to_vec2()); + let area = u.cross(v); + if !(area.is_finite() && area != 0.0) { + self.warn(FLAT_IMAGES); + return None; + } + if (im.brightness, im.contrast, im.fade) != (50, 50, 0) { + self.warn(IMAGE_ADJUSTMENTS); + } + if has_display && im.display & 8 == 0 { + self.warn(OPAQUE_IMAGES); + } + let clip = if !im.clipping || (has_display && im.display & 4 == 0) { + None + } else if im.clip_inverted { + self.warn(INVERTED_CLIPS); + None + } else { + image_clip(im) + }; + Some(Geom::Image(ImageItem { def: im.image_def, insert: point(im.insert), u, v, size: im.size, clip })) + } + fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option { // Meshes are in world coordinates, seen from above. if p.is_polyface() || p.is_mesh() { @@ -456,6 +514,27 @@ fn in_range(g: &Geom) -> bool { } Geom::Text(t) => origin(&t.xf) && t.height <= MAX_COORD, Geom::Insert(i) => i.cells.iter().all(|m| origin(m) && m.as_coeffs().iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)), + Geom::Image(i) => { + let [w, h] = i.size; + let far = i.insert + i.u * w + i.v * h; + near(i.insert) && near(far) && [i.u.x, i.u.y, i.v.x, i.v.y, w, h].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD) + } + } +} + +/// The clip boundary of IMAGE `im` in pixel space ([`ImageItem::placement`]): two opposite corners +/// of a rectangle, or a polygon of three points or more. The boundary's points are pixel centres +/// counted from the top-left pixel, so the image's own corners are at (−0.5, −0.5) and +/// (width − 0.5, height − 0.5). `None` when it has too few points. +fn image_clip(im: &model::Image) -> Option> { + let pts: Vec = im.clip.iter().map(|[x, y]| Point::new(x + 0.5, y + 0.5)).collect(); + match pts.as_slice() { + [a, b] if im.clip_type == 1 => { + let (x0, x1, y0, y1) = (a.x.min(b.x), a.x.max(b.x), a.y.min(b.y), a.y.max(b.y)); + Some(vec![Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)]) + } + p if p.len() >= 3 => Some(p.to_vec()), + _ => None, } } @@ -479,6 +558,7 @@ fn is_known(kind: &str) -> bool { | "MTEXT" | "INSERT" | "DIMENSION" + | "IMAGE" | "ATTDEF" | "SEQEND" | "VERTEX" diff --git a/crates/cad/src/import/reader.rs b/crates/cad/src/import/reader.rs index bfa1293b8d..1adc71c563 100644 --- a/crates/cad/src/import/reader.rs +++ b/crates/cad/src/import/reader.rs @@ -1,5 +1,5 @@ //! What the import uses of a drawing, from `craft_dxf::model`: header variables; the layer, -//! linetype and text style tables; the blocks; the entities; the layouts. +//! linetype and text style tables; the blocks; the entities; the layouts; the image files. use std::collections::{HashMap, HashSet}; use std::rc::Rc; @@ -50,6 +50,15 @@ pub(crate) struct BlockDef<'a> { pub xref: bool, } +/// A raster image file that IMAGE entities show (an IMAGEDEF object). +#[derive(Clone, Debug)] +pub(crate) struct ImageFile { + /// The file's path as the drawing stores it (absolute, or relative to the drawing). + pub path: String, + /// Its size in pixels (0 when not given). + pub size: [f64; 2], +} + /// A layout: model space, or a paper layout with the block holding its art. #[derive(Clone, Debug)] pub(crate) struct LayoutDef { @@ -80,6 +89,8 @@ pub(crate) struct Drawing<'a> { pub entities: Vec>, /// Model space first, then the paper layouts in tab order. pub layouts: Vec, + /// The image files by the handle of their IMAGEDEF. + pub images: HashMap, /// How many sections the file has (none: not a drawing). pub sections: usize, /// The binary solid-modeler data of the regions, by handle (DXF 2013 and later keep it in @@ -116,6 +127,11 @@ impl<'a> Drawing<'a> { } let block_names = doc.block_names(); d.layouts = layouts(&doc, &block_names); + for def in doc.objects_of("IMAGEDEF").map(model::objects::ImageDef::read) { + if let Some(h) = def.handle { + d.images.entry(h).or_insert(ImageFile { path: def.file, size: def.size }); + } + } d.regions = Rc::new(region_data(&doc)); for b in doc.blocks { if b.name.is_empty() { diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs new file mode 100644 index 0000000000..9d85ca08ba --- /dev/null +++ b/crates/cad/src/import/tests_image.rs @@ -0,0 +1,620 @@ +//! Raster images: an IMAGE comes in as an image linked to the file its IMAGEDEF names, placed as +//! its corner and pixel vectors say and clipped by its clip boundary; images the export wrote come +//! back where they were. + +use std::sync::Arc; + +use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind, Unit}; +use vectorcraft_geom::{Affine, Point, Rect}; + +use super::*; +use crate::{DxfOptions, DxfVersion}; + +/// A DXF file of `entities` and `objects` (each a run of pairs). +fn drawing(entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec { + with_blocks(&[], entities, objects) +} + +/// A DXF file of `blocks`, `entities` and `objects` (each a run of pairs). +fn with_blocks(blocks: &[(i32, &str)], entities: &[(i32, &str)], objects: &[(i32, &str)]) -> Vec { + let mut p: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")]; + p.extend([(0, "SECTION"), (2, "BLOCKS")]); + p.extend_from_slice(blocks); + p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "ENTITIES")]); + p.extend_from_slice(entities); + p.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]); + p.extend_from_slice(objects); + p.extend([(0, "ENDSEC"), (0, "EOF")]); + p.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect::().into_bytes() +} + +/// An IMAGEDEF with handle `handle` naming `file`, 30 × 10 pixels. +fn def<'a>(handle: &'a str, file: &'a str) -> Vec<(i32, &'a str)> { + vec![(0, "IMAGEDEF"), (5, handle), (100, "AcDbRasterImageDef"), (1, file), (10, "30"), (20, "10")] +} + +/// An IMAGE of IMAGEDEF `def` with its lower-left corner at (10, 20) and 2-unit pixels, `size` +/// pixels (none given: `None`), followed by `more` groups. +fn image<'a>(def: &'a str, size: Option<(&'a str, &'a str)>, more: &[(i32, &'a str)]) -> Vec<(i32, &'a str)> { + let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "0"), (22, "2")]; + if let Some((w, h)) = size { + e.extend([(13, w), (23, h)]); + } + e.push((340, def)); + e.extend_from_slice(more); + e +} + +/// Points at 1:1, not centred: drawing (x, y) lands at document (x, artboard height − y). +fn points() -> ImportOptions { + ImportOptions { unit: Some(Unit::Points), scale: Some(1.0), center: false, ..ImportOptions::default() } +} + +fn nodes(doc: &Document) -> Vec { + let mut out = vec![]; + doc.walk(|n| out.push(n.clone())); + out +} + +fn images(doc: &Document) -> Vec { + nodes(doc) + .into_iter() + .filter_map(|n| match n.kind { + NodeKind::Image(im) => Some(*im), + _ => None, + }) + .collect() +} + +/// Where image `im`'s pixel corner `(x, y)` lands. +fn at(im: &ImageObject, x: f64, y: f64) -> Point { + im.xf * Point::new(x, y) +} + +fn near(a: Point, b: Point) -> bool { + a.distance(b) < 1e-9 +} + +#[test] +fn an_image_comes_in_linked_to_its_file_with_its_top_left_pixel_at_the_top_left() { + let bytes = drawing(&image("1F", Some(("30", "10")), &[]), &def("1F", r"photos\scan.png")); + let r = import(&bytes, &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("left out")), "{:?}", r.warnings); + let doc = &r.document; + assert_eq!(doc.layers.iter().filter_map(|l| l.name.as_deref()).collect::>(), ["Photos"]); + let ims = images(doc); + assert_eq!(ims.len(), 1); + let im = &ims[0]; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(r"photos\scan.png")); + assert_eq!((im.width, im.height), (30, 10)); + // The drawing's 60 × 20 units from (10, 20): y up there, y down here. + let h = doc.artboards[0].rect.height(); + assert!(near(at(im, 0.0, 0.0), Point::new(10.0, h - 40.0)), "{:?}", at(im, 0.0, 0.0)); + assert!(near(at(im, 30.0, 10.0), Point::new(70.0, h - 20.0)), "{:?}", at(im, 30.0, 10.0)); + // Until its file is read it shows the placeholder. + assert!(doc.images.get(&im.key).is_some_and(ImageBlob::is_proxy)); +} + +#[test] +fn an_image_without_its_own_size_takes_its_file_s_and_two_images_of_one_file_share_its_data() { + let mut e = image("1F", None, &[]); + e.extend(image("1F", Some(("30", "10")), &[])); + let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document; + let ims = images(&doc); + assert_eq!(ims.iter().map(|im| (im.width, im.height)).collect::>(), [(30, 10), (30, 10)]); + assert_eq!(ims[0].key, ims[1].key); + assert_eq!(doc.images.len(), 1); +} + +#[test] +fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() { + // Pixels 5 to 14 across and 2 to 6 down: a 20 × 10 unit window. + let part = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]); + let r = import(&drawing(&part, &def("1F", "scan.png")), &points()).unwrap(); + let all = nodes(&r.document); + let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group"); + let children = group.children().unwrap(); + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::Image(_))); + let h = r.document.artboards[0].rect.height(); + let clip = children[0].geometric_bounds().unwrap(); + // x 10 + 2·5 to 10 + 2·15; y down from the image's top (20 + 2·10) 2·2 to 2·7. + let want = Rect::new(20.0, h - 40.0 + 4.0, 40.0, h - 40.0 + 14.0); + assert!([(clip.x0, want.x0), (clip.y0, want.y0), (clip.x1, want.x1), (clip.y1, want.y1)].iter().all(|(a, b)| (a - b).abs() < 1e-9), "{clip:?}"); + // The default boundary, the whole image, makes no group; clipping off ignores a boundary. + let whole = image("1F", Some(("30", "10")), &[(280, "1"), (71, "1"), (91, "2"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "9.5")]); + let off = image("1F", Some(("30", "10")), &[(280, "0"), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]); + for e in [whole, off] { + let doc = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap().document; + assert!(!nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { .. })), "no clip group"); + assert_eq!(images(&doc).len(), 1); + } +} + +#[test] +fn a_clip_boundary_with_a_repeated_corner_still_clips_the_image() { + let boundary = image( + "1F", + Some(("30", "10")), + &[ + (280, "1"), + (71, "2"), + (91, "4"), + (14, "-0.5"), + (24, "-0.5"), + (14, "29.5"), + (24, "-0.5"), + (14, "-0.5"), + (24, "-0.5"), + (14, "-0.5"), + (24, "9.5"), + ], + ); + let doc = import(&drawing(&boundary, &def("1F", "scan.png")), &points()).unwrap().document; + let all = nodes(&doc); + let group = all.iter().find(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })).expect("a clip group"); + let children = group.children().unwrap(); + assert!(matches!(children[0].kind, NodeKind::Path { clipping: true, .. })); + assert!(matches!(children[1].kind, NodeKind::Image(_))); +} + +#[test] +fn image_display_flags_control_clipping_only_when_present() { + for (display, clipping, clipped) in [(None, "1", true), (Some("9"), "1", false), (Some("13"), "1", true), (Some("13"), "0", false)] { + let mut boundary = vec![(280, clipping), (71, "1"), (91, "2"), (14, "4.5"), (24, "1.5"), (14, "14.5"), (24, "6.5")]; + if let Some(flags) = display { + boundary.push((70, flags)); + } + let e = image("1F", Some(("30", "10")), &boundary); + let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap(); + assert_eq!(images(&r.document).len(), 1); + assert_eq!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), clipped, "{display:?}, {clipping}"); + } +} + +#[test] +fn images_requested_opaque_warn_once_and_other_images_do_not() { + for (display, opaque) in [(None, false), (Some("9"), false), (Some("1"), true), (Some("5"), true)] { + let flags: Vec<_> = display.map(|flags| (70, flags)).into_iter().collect(); + let mut e = image("1F", Some(("30", "10")), &flags); + e.extend(image("1F", Some(("30", "10")), &flags)); + let r = import(&drawing(&e, &def("1F", "scan.png")), &points()).unwrap(); + assert_eq!(images(&r.document).len(), 2); + let warnings: Vec<_> = r.warnings.iter().filter(|w| w.contains("opaque") && w.contains("transparency")).collect(); + assert_eq!(warnings.len(), usize::from(opaque), "{display:?}: {:?}", r.warnings); + } +} + +#[test] +fn a_polygon_clip_keeps_its_points_and_an_inverted_clip_shows_the_whole_image_with_a_warning() { + let tri = image( + "1F", + Some(("30", "10")), + &[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")], + ); + let doc = import(&drawing(&tri, &def("1F", "scan.png")), &points()).unwrap().document; + let clip = nodes(&doc).into_iter().find(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).expect("a clip path"); + let NodeKind::Path { path, .. } = &clip.kind else { panic!("not a path") }; + let im = &images(&doc)[0]; + let mut corners: Vec = path.to_bezpath().elements().iter().filter_map(|el| el.end_point()).collect(); + // The path may draw its closing edge as a line back to the start. + if corners.len() > 1 && corners.first() == corners.last() { + corners.pop(); + } + assert_eq!(corners.len(), 3, "{corners:?}"); + for (c, (x, y)) in corners.iter().zip([(0.0, 0.0), (30.0, 0.0), (0.0, 10.0)]) { + assert!(near(*c, at(im, x, y)), "{c:?}"); + } + // The same triangle closed by repeating its first point still clips: three corners of the + // image's box and a repeat are not the box. + let closed = image( + "1F", + Some(("30", "10")), + &[ + (280, "1"), + (71, "2"), + (91, "4"), + (14, "-0.5"), + (24, "-0.5"), + (14, "29.5"), + (24, "-0.5"), + (14, "29.5"), + (24, "9.5"), + (14, "-0.5"), + (24, "-0.5"), + ], + ); + let doc = import(&drawing(&closed, &def("1F", "scan.png")), &points()).unwrap().document; + assert!(nodes(&doc).iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. })), "a clip group"); + // A clip point far out of range leaves the image out. + let far = image( + "1F", + Some(("30", "10")), + &[(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")], + ); + let r = import(&drawing(&far, &def("1F", "scan.png")), &points()).unwrap(); + assert!(images(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let mut inverted = tri.clone(); + inverted.push((290, "1")); + let r = import(&drawing(&inverted, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Group { .. }))); + assert!(r.warnings.iter().any(|w| w.contains("inverted image clips")), "{:?}", r.warnings); +} + +#[test] +fn images_without_usable_file_references_do_not_expand_the_artboard() { + for objects in [def("1F", "scan.png"), def("2A", " ")] { + let mut far = image("2A", Some(("30", "10")), &[]); + for (code, value) in &mut far { + if *code == 10 || *code == 20 { + *value = "100000"; + } + } + let mut entities = vec![(0, "LINE"), (10, "0"), (20, "0"), (11, "100"), (21, "50")]; + entities.extend(far); + let r = import(&drawing(&entities, &objects), &points()).unwrap(); + assert!(images(&r.document).is_empty()); + assert!(r.warnings.iter().any(|w| w.contains("name no image file")), "{:?}", r.warnings); + assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { .. }))); + let board = r.document.artboards[0].rect; + assert!(board.width() < 1000.0 && board.height() < 1000.0, "{board:?}"); + } +} + +/// Entities, objects, and the warning they give. +type Case<'a> = (Vec<(i32, &'a str)>, Vec<(i32, &'a str)>, &'a str); + +#[test] +fn images_that_name_no_file_or_have_no_size_or_area_are_left_out_with_warnings() { + let cases: [Case; 4] = [ + (image("2A", Some(("30", "10")), &[]), def("1F", "scan.png"), "name no image file"), + (image("1F", Some(("30", "10")), &[]), def("1F", " "), "name no image file"), + (image("1F", Some(("0", "10")), &[]), vec![(0, "IMAGEDEF"), (5, "1F"), (1, "scan.png")], "no size in pixels"), + ( + vec![(0, "IMAGE"), (10, "10"), (20, "20"), (11, "2"), (21, "0"), (12, "4"), (22, "0"), (13, "30"), (23, "10"), (340, "1F")], + def("1F", "scan.png"), + "no width or height", + ), + ]; + for (e, o, why) in cases { + let r = import(&drawing(&e, &o), &points()).unwrap(); + assert!(images(&r.document).is_empty(), "{why}"); + assert!(r.warnings.iter().any(|w| w.contains(why)), "{why}: {:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "an IMAGE is not an unknown entity: {:?}", r.warnings); + } + // Brightness, contrast and fade are noted. + let faded = image("1F", Some(("30", "10")), &[(283, "40")]); + let r = import(&drawing(&faded, &def("1F", "scan.png")), &points()).unwrap(); + assert_eq!(images(&r.document).len(), 1); + assert!(r.warnings.iter().any(|w| w.contains("fade")), "{:?}", r.warnings); +} + +#[test] +fn an_image_whose_show_image_flag_is_off_is_hidden() { + let o = def("1F", "scan.png"); + for (flags, shown) in [("3", 1), ("1", 1), ("2", 0), ("0", 0)] { + let r = import(&drawing(&image("1F", Some(("30", "10")), &[(70, flags)]), &o), &points()).unwrap(); + assert_eq!(images(&r.document).len(), shown, "group 70 = {flags}"); + assert!(!r.warnings.iter().any(|w| w.contains("of these types")), "{:?}", r.warnings); + } +} + +#[test] +fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_on_the_canvas() { + // The block's image sits 10,000,000 units out, and the insert moves it back next to the origin. + let tri = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "29.5"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + let mut far = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10000010"), (20, "20")]; + far.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]); + let head = far.len(); + far.extend_from_slice(&tri); + let block_of = |image: &[(i32, &'static str)]| { + let mut block = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]; + block.extend_from_slice(image); + block.push((0, "ENDBLK")); + block + }; + let insert = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-10000000"), (20, "0")]; + let r = import(&with_blocks(&block_of(&far), &insert, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let art = &r.document.symbols.first().expect("a symbol").art; + assert!(matches!(art.kind, NodeKind::Group { clip: true, .. }), "{:?}", art.kind); + // A clip point far from its own image in the block still leaves the image out. + let mut farther = far[..head].to_vec(); + farther.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "1e308"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]); + let r = import(&with_blocks(&block_of(&farther), &insert, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + // A wide image whose corner is far out, cropped to a part near the origin, comes in too. + let mut wide = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "-5000000"), (20, "0")]; + wide.extend([(11, "1000"), (21, "0"), (12, "0"), (22, "1000"), (13, "10000"), (23, "10"), (340, "1F")]); + wide.extend([(280, "1"), (71, "2"), (91, "3"), (14, "5200"), (24, "0"), (14, "5400"), (24, "0"), (14, "5200"), (24, "5")]); + let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]; + let r = import(&with_blocks(&block_of(&wide), &at_origin, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + assert!(r.document.symbols.first().is_some_and(|s| matches!(s.art.kind, NodeKind::Group { clip: true, .. }))); + // A block's image near the origin whose clip reaches out of range where the insert places it + // is left out with that warning, and the block's other art stays. + let mut reaching = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, "10"), (20, "20")]; + reaching.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]); + reaching.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]); + reaching.extend([(0, "LINE"), (8, "Photos"), (10, "0"), (20, "0"), (11, "50"), (21, "50")]); + let r = import(&with_blocks(&block_of(&reaching), &at_origin, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let placed = nodes(&r.document); + assert!(!placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. } | NodeKind::Image(_)))); + assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's line"); + // The block's symbol has no instance left, so it is not kept with the image it holds. + assert!(r.document.symbols.is_empty(), "{:?}", r.document.symbols.iter().map(|s| &s.name).collect::>()); +} + +#[test] +fn a_symbol_that_only_placements_drawn_as_art_use_is_not_charged_twice() { + // Block B holds a 600,000-point polyline and an image whose clip reaches out of range where an + // insert at the origin places it, so that insert draws B's art instead of an instance. + let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]; + owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]); + owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]); + owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]); + owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into())]); + owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]); + for i in 0..600_000 { + owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]); + } + owned.push((0, "ENDBLK".into())); + let block: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let at_origin = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]; + let r = import(&with_blocks(&block, &at_origin, &def("1F", "scan.png")), &points()).unwrap(); + // 1,200,000 points if the unused symbol stayed charged: past the tests' limit of 1,000,000. + assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); + assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the block's polyline"); + assert!(r.document.symbols.is_empty()); + // A second insert that places B in range makes the symbol again, which is charged again: its + // polyline no longer fits, and the first insert's stays. + let both = [(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0"), (0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-2000000"), (20, "0")]; + let r = import(&with_blocks(&block, &both, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); + let placed = nodes(&r.document); + assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "the first insert's polyline"); + assert!(placed.iter().any(|n| matches!(n.kind, NodeKind::SymbolInstance { .. })), "the second insert's instance"); + assert_eq!(r.document.symbols.len(), 1); +} + +#[test] +fn a_symbol_that_only_a_removed_symbol_placed_is_removed_with_it() { + // Block B holds a 600,000-point polyline and an image whose clip reaches out of range where the + // drawing's insert of block A, which places B, puts it. That insert draws A's art and removes + // A's symbol; B's symbol, which only A's art placed, goes too, so drawing B's art fits. + let mut owned: Vec<(i32, String)> = vec![(0, "BLOCK".into()), (2, "B".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]; + owned.extend([(0, "LWPOLYLINE".into()), (8, "Photos".into()), (90, "600000".into()), (70, "0".into())]); + for i in 0..600_000 { + owned.extend([(10, format!("{}", i % 100)), (20, format!("{}", i / 100))]); + } + owned.extend([(0, "IMAGE".into()), (8, "Photos".into()), (100, "AcDbRasterImage".into()), (10, "10".into()), (20, "20".into())]); + owned.extend([(11, "2".into()), (21, "0".into()), (12, "0".into()), (22, "2".into()), (13, "30".into()), (23, "10".into())]); + owned.extend([(340, "1F".into()), (280, "1".into()), (71, "2".into()), (91, "3".into()), (14, "-0.5".into()), (24, "-0.5".into())]); + owned.extend([(14, "2000010".into()), (24, "-0.5".into()), (14, "-0.5".into()), (24, "9.5".into()), (0, "ENDBLK".into())]); + owned.extend([(0, "BLOCK".into()), (2, "A".into()), (70, "0".into()), (10, "0".into()), (20, "0".into())]); + owned.extend([(0, "INSERT".into()), (8, "Photos".into()), (2, "B".into()), (10, "0".into()), (20, "0".into()), (0, "ENDBLK".into())]); + let blocks: Vec<(i32, &str)> = owned.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0")]; + let r = import(&with_blocks(&blocks, &insert, &def("1F", "scan.png")), &points()).unwrap(); + assert!(!r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); + assert!(nodes(&r.document).iter().any(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })), "B's polyline"); + assert!(r.document.symbols.is_empty()); +} + +/// Block B holds an image clipped by a triangle with a corner at (`far`, −0.5) in pixel space, and +/// block A places B by `inner` beside an image of its own clipped near it; the drawing places A +/// at the origin scaled by `outer`. +fn nested(far: &'static str, inner: &[(i32, &'static str)], outer: &'static str) -> Vec { + let clipped = |x: &'static str, corner: &'static str| { + let mut e = vec![(0, "IMAGE"), (8, "Photos"), (100, "AcDbRasterImage"), (10, x), (20, "20")]; + e.extend([(11, "2"), (21, "0"), (12, "0"), (22, "2"), (13, "30"), (23, "10"), (340, "1F")]); + e.extend([(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, corner), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]); + e + }; + let mut blocks = vec![(0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]; + blocks.extend(clipped("10", far)); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "A"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]); + blocks.extend_from_slice(inner); + blocks.extend(clipped("100", "29.5")); + blocks.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (8, "Photos"), (2, "A"), (10, "0"), (20, "0"), (41, outer), (42, outer)]; + with_blocks(&blocks, &insert, &def("1F", "scan.png")) +} + +#[test] +fn a_block_s_clip_point_beyond_any_usable_range_leaves_its_image_out_even_where_inserts_scale_it_back() { + // B's clip corner is 2e19 units out in its own space, and two inserts at the smallest scale + // would bring it back next to the origin. + let r = import(&nested("1e19", &[(41, "1e-12"), (42, "1e-12")], "1e-12"), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + let mut held = 0; + for s in &r.document.symbols { + s.art.walk(&mut |n: &Node| held += usize::from(matches!(n.kind, NodeKind::Image(_)))); + } + assert_eq!(held + images(&r.document).len(), 1, "A's own image"); +} + +#[test] +fn a_clip_reach_placed_by_an_overflowing_transform_is_unbounded() { + use super::build::placed_reach; + let out = |b: Rect| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite()); + // Across, the terms of every corner overflow with opposite signs to NaN, which a union with + // another symbol's reach would drop; the reach is unbounded instead. + let h = 1e300; + let xf = Affine::new([h, 1.0, -h, 1.0, 0.0, 0.0]); + let r = Rect::new(1e10, 1e10, 2e10, 2e10); + let near = Rect::new(0.0, 0.0, 10.0, 10.0); + let whole = placed_reach(xf, r); + assert!(out(whole.union(near)), "{whole:?}"); + // An unbounded reach stays unbounded wherever it is placed. + assert!(out(placed_reach(Affine::scale(1e-12), whole).union(near))); + assert!(out(placed_reach(Affine::IDENTITY, whole).union(near))); + // A placement that stays finite is the box of the placed corners. + let b = placed_reach(Affine::new([0.0, 1.0, -1.0, 0.0, 5.0, 0.0]), near); + assert_eq!((b.x0, b.y0, b.x1, b.y1), (-5.0, 0.0, 5.0, 10.0)); +} + +#[test] +fn clip_paths_count_against_the_path_point_limit() { + // A 1,000-point clip in an anonymous block placed 1,100 times: 1,001,000 path elements, past + // the tests' limit of 1,000,000. + let mut clip: Vec<(i32, String)> = vec![(280, "1".into()), (71, "2".into()), (91, "1000".into())]; + for i in 0..1000 { + let a = f64::from(i) * std::f64::consts::TAU / 1000.0; + clip.extend([(14, format!("{}", 14.5 + 10.0 * a.cos())), (24, format!("{}", 4.5 + 4.0 * a.sin()))]); + } + let clip: Vec<(i32, &str)> = clip.iter().map(|(c, v)| (*c, v.as_str())).collect(); + let mut block = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + block.extend(image("1F", Some(("30", "10")), &clip)); + block.push((0, "ENDBLK")); + let insert = [(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, "1100"), (44, "100")]; + let r = import(&with_blocks(&block, &insert, &def("1F", "scan.png")), &points()).unwrap(); + let clips = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: true, .. })).count(); + assert!((900..1000).contains(&clips), "{clips} clip paths"); + assert!(r.warnings.iter().any(|w| w.contains("path points")), "{:?}", r.warnings); +} + +#[test] +fn an_insert_drawn_as_art_gets_back_its_unused_symbol_s_objects_at_the_object_limit() { + // Block B holds a line and an image whose clip reaches out of range where B's insert places + // it: 4 objects as a symbol. 99,996 lines before it leave exactly room for that symbol under + // the tests' limit of 100,000 objects, so its insert draws B's art in the room the unused + // symbol gives back. + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]); + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]); + let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + blocks.extend(image("1F", Some(("30", "10")), &reaching)); + blocks.push((0, "ENDBLK")); + // An insert makes at most 10,000 copies: nine of 100 × 100 and one of 84 × 119. + let mut entities = vec![]; + for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("84", "119")]) { + entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]); + } + entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "0"), (20, "0")]); + let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("clip boundaries reach out of range")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings); + let lines = nodes(&r.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { clipping: false, .. })).count(); + assert_eq!(lines, 99_997, "the lines and B's line"); + assert!(r.document.symbols.is_empty()); +} + +#[test] +fn copies_drawn_as_art_past_the_object_limit_stop_without_looking_at_the_block() { + // Block B: 200 lines and an image whose clip reaches out of range unless its copy sits left of + // the origin. 99,796 lines, B's symbol and the first copy's instance fill the tests' limit of + // 100,000 objects; the next 9,999 copies would each look at B's 201 items, past the tests' + // block-work limit of 1,000,000. + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]); + for _ in 0..200 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]); + } + let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + blocks.extend(image("1F", Some(("30", "10")), &reaching)); + blocks.push((0, "ENDBLK")); + let mut entities = vec![]; + for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("79", "124")]) { + entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]); + } + entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-35"), (20, "0"), (70, "10000"), (44, "10")]); + let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +#[test] +fn copies_of_a_symbol_taken_out_at_the_object_limit_are_not_drawn_again() { + // Block B: an image whose clip reaches out of range only for the first copy, and 200 lines. + // 99,800 lines and the first copy, drawn as art in the room its unused symbol gives back, + // fill the tests' limit of 100,000 objects; each of the next 9,999 copies would draw the + // symbol again from B's 201 items, past the tests' block-work limit of 1,000,000. + let mut blocks = vec![(0, "BLOCK"), (2, "*U1"), (70, "1"), (10, "0"), (20, "0")]; + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "0"), (11, "1"), (21, "0")]); + blocks.extend([(0, "ENDBLK"), (0, "BLOCK"), (2, "B"), (70, "0"), (10, "0"), (20, "0")]); + let reaching = [(280, "1"), (71, "2"), (91, "3"), (14, "-0.5"), (24, "-0.5"), (14, "2000010"), (24, "-0.5"), (14, "-0.5"), (24, "9.5")]; + blocks.extend(image("1F", Some(("30", "10")), &reaching)); + for _ in 0..200 { + blocks.extend([(0, "LINE"), (8, "0"), (10, "0"), (20, "50"), (11, "5"), (21, "50")]); + } + blocks.push((0, "ENDBLK")); + let mut entities = vec![]; + for (cols, rows) in std::iter::repeat_n(("100", "100"), 9).chain([("98", "100")]) { + entities.extend([(0, "INSERT"), (2, "*U1"), (10, "0"), (20, "0"), (70, cols), (71, rows), (44, "1"), (45, "1")]); + } + entities.extend([(0, "INSERT"), (8, "Photos"), (2, "B"), (10, "-25"), (20, "0"), (70, "10000"), (44, "-10")]); + let r = import(&with_blocks(&blocks, &entities, &def("1F", "scan.png")), &points()).unwrap(); + assert!(r.warnings.iter().any(|w| w.contains("objects: the rest")), "{:?}", r.warnings); + assert!(!r.warnings.iter().any(|w| w.contains("too much work")), "{:?}", r.warnings); +} + +/// A document with a 4 × 2 pixel image, 5 pt pixels, its top-left corner at (10, 20). +fn image_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 4, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 0, 255, 255].repeat(8), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = Document::new(200.0, 100.0); + let layer = d.add_layer(Some("Photos")); + let im = ImageObject { + key: "raster-1".into(), + width: 4, + height: 2, + xf: Affine::translate((10.0, 20.0)) * Affine::scale(5.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.insert(Some(layer), usize::MAX, n).unwrap(); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None, file_font: Default::default() }); + d +} + +/// Import `bytes`, written from [`image_doc`], and check its one image: linked to `name`, the file +/// the export wrote, and the size and way up it had. +fn written_and_read(bytes: &[u8], name: &str) { + let doc = import(bytes, &points()).unwrap().document; + let ims = images(&doc); + assert_eq!(ims.len(), 1, "{:?}", nodes(&doc).iter().map(|n| &n.kind).collect::>()); + let im = &ims[0]; + assert_eq!(im.link.as_ref().map(|l| l.path.as_str()), Some(name)); + assert_eq!((im.width, im.height), (4, 2)); + // 20 × 10 pt with the top-left pixel at the top-left, as it was. + let (tl, br) = (at(im, 0.0, 0.0), at(im, 4.0, 2.0)); + assert!((br.x - tl.x - 20.0).abs() < 1e-6 && (br.y - tl.y - 10.0).abs() < 1e-6, "{tl:?} {br:?}"); +} + +#[test] +fn an_image_the_export_wrote_comes_back_linked_to_the_file_it_wrote() { + let d = image_doc(); + let out = crate::export(&d, &DxfOptions { region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }).unwrap(); + assert_eq!(out.images.len(), 1); + written_and_read(&out.bytes, &out.images[0].name); +} + +#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))] +#[test] +fn an_image_in_a_dwg_drawing_comes_in_as_in_its_dxf() { + let d = image_doc(); + let o = DxfOptions { version: DxfVersion::R2000, region: d.artboards[0].rect, unit: Unit::Points, ..DxfOptions::default() }; + let out = crate::export(&d, &o).unwrap(); + crate::dwg::allow_in_process(); + let dwg = craft_dwg::dxf_to_dwg_as(&out.bytes, "AC1018").unwrap(); + written_and_read(&dwg, &out.images[0].name); +} diff --git a/crates/engine/src/cmd/fileio/dxfimport.rs b/crates/engine/src/cmd/fileio/dxfimport.rs index 2d16034c09..c621c66bad 100644 --- a/crates/engine/src/cmd/fileio/dxfimport.rs +++ b/crates/engine/src/cmd/fileio/dxfimport.rs @@ -76,6 +76,16 @@ pub(super) fn import(bytes: &[u8], o: &ImportOptions) -> Result<(Document, Vec Vec { + missing + .iter() + .filter_map(|row| row["name"].as_str()) + .map(|name| format!("linked image '{name}' wasn't found: a placeholder keeps its place until it is relinked")) + .collect() +} + const INFO: &str = "document.dxfInfo"; fn dxf_info(_: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/cmd/fileio/load.rs b/crates/engine/src/cmd/fileio/load.rs index d434dcf6ec..76f793f302 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -920,6 +920,9 @@ impl ReadFile { let Some((update_links, low_res_proxy_eps)) = self.links_left.take() else { return }; let base = crate::cmd::links::LinkBase::file(self.path.as_deref()); self.links = crate::cmd::links::resolve(&mut self.loaded.doc, base, update_links, low_res_proxy_eps); + if matches!(self.loaded.format.id, "dxf" | "dwg") { + self.loaded.warnings.extend(super::dxfimport::missing_image_notes(&self.links.missing)); + } for note in Session::refresh_text_bounds(&mut self.loaded.doc) { if !self.loaded.warnings.contains(¬e) { self.loaded.warnings.push(note); diff --git a/crates/engine/src/cmd/fileio/tests_dxfimport.rs b/crates/engine/src/cmd/fileio/tests_dxfimport.rs index 83bf8a5ea3..f3ac8b50fb 100644 --- a/crates/engine/src/cmd/fileio/tests_dxfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dxfimport.rs @@ -1,6 +1,6 @@ //! DXF through the commands: `document.open` with the DXF options, `document.dxfInfo`, //! File → Place of a drawing (fitted, centred or at its origin), the format table, binary files, -//! and a drawing `document.export` wrote opened again. +//! a drawing `document.export` wrote opened again, and the image files a drawing links to. use serde_json::{Value, json}; use vectorcraft_doc::{Node, NodeKind}; @@ -268,3 +268,102 @@ fn a_drawing_export_writes_opens_again() { let union = all.iter().copied().reduce(|a, b| a.union(b)).unwrap(); assert!((union.width() - 350.0).abs() < 2.0 && (union.y1 - h + 200.0).abs() < 2.0, "{union:?} on {h}"); } + +/// A folder of a drawing linking `img\photo.png`, a 30 × 20 pixel PNG beside it, and `gone.png`, +/// which isn't there (removed when dropped). +struct Linked(std::path::PathBuf); + +impl Linked { + fn new(tag: &str) -> Self { + let dir = std::env::temp_dir().join(format!("vectorcraft-dxfimage-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("img")).unwrap(); + let img = craft_image_codecs::Image::from_raw( + 30, + 20, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [230u8, 20, 20, 255].repeat(600), + ) + .unwrap(); + let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + std::fs::write(dir.join("img").join("photo.png"), png).unwrap(); + let image = |def: &'static str, x: &'static str| { + vec![(0, "IMAGE"), (8, "0"), (10, x), (20, "0"), (11, "1"), (21, "0"), (12, "0"), (22, "1"), (13, "30"), (23, "20"), (340, def)] + }; + let mut pairs: Vec<(i32, &str)> = vec![(0, "SECTION"), (2, "HEADER"), (9, "$ACADVER"), (1, "AC1015"), (0, "ENDSEC")]; + pairs.extend([(0, "SECTION"), (2, "ENTITIES")]); + pairs.extend(image("1F", "0")); + pairs.extend(image("2A", "100")); + pairs.extend([(0, "ENDSEC"), (0, "SECTION"), (2, "OBJECTS")]); + pairs.extend([(0, "IMAGEDEF"), (5, "1F"), (1, r"img\photo.png"), (10, "30"), (20, "20")]); + pairs.extend([(0, "IMAGEDEF"), (5, "2A"), (1, "gone.png"), (10, "30"), (20, "20")]); + pairs.extend([(0, "ENDSEC"), (0, "EOF")]); + let text: String = pairs.iter().map(|(c, v)| format!("{c:>3}\n{v}\n")).collect(); + std::fs::write(dir.join("plan.dxf"), text).unwrap(); + Self(dir) + } + + fn drawing(&self) -> String { + self.0.join("plan.dxf").to_string_lossy().into_owned() + } +} + +impl Drop for Linked { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// The images of the active document: each one's link's file name, size, and whether its pixels +/// are its file's (not the placeholder). +fn images(s: &Session) -> Vec<(String, (u32, u32), bool)> { + let st = s.doc().unwrap(); + let mut out = vec![]; + st.doc.visit_images(|_, im| { + let read = st.doc.images.get(&im.key).is_some_and(|b| !b.is_proxy()); + out.push((im.link.as_ref().map(|l| l.name().to_string()).unwrap_or_default(), (im.width, im.height), read)); + }); + out +} + +#[test] +fn opening_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() { + let dir = Linked::new("open"); + let mut s = Session::new(); + let r = s.execute("document.open", &json!({"path": dir.drawing()})).unwrap(); + assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]); + let missing = r["missingLinks"].as_array().unwrap(); + assert_eq!(missing.iter().map(|m| m["name"].as_str()).collect::>(), [Some("gone.png")], "{r}"); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}"); + assert!(!warnings.iter().any(|w| w.contains("photo.png")), "{warnings:?}"); +} + +#[test] +fn placing_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones() { + let dir = Linked::new("place"); + let mut s = page(); + let r = s.execute("file.place", &json!({"path": dir.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap(); + assert_eq!(images(&s), [("photo.png".to_string(), (30, 20), true), ("gone.png".to_string(), (30, 20), false)]); + let warnings: Vec<&str> = r["warnings"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(warnings.iter().any(|w| w.contains("'gone.png' wasn't found")), "{warnings:?}"); +} + +#[test] +fn placing_a_drawing_keeps_missing_links_anchored_to_its_folder() { + let source = Linked::new("place-missing-source"); + let destination = Linked::new("place-missing-destination"); + let mut s = page(); + s.doc_mut().unwrap().path = Some(destination.0.join("art.vectorcraft").to_string_lossy().into_owned()); + s.execute("file.place", &json!({"path": source.drawing(), "dxf": {"unit": "pt", "scale": 1}})).unwrap(); + let mut missing = vec![]; + s.doc().unwrap().doc.visit_images(|_, im| { + if let Some(link) = im.link.as_ref().filter(|link| link.name() == "gone.png") { + missing.push(std::path::PathBuf::from(&link.path)); + } + }); + assert_eq!(missing, [source.0.join("gone.png")]); + assert!(missing[0].is_absolute()); + assert!(!missing[0].starts_with(&destination.0)); +} diff --git a/crates/engine/src/cmd/links.rs b/crates/engine/src/cmd/links.rs index 92171a0b71..a9fa0d6d54 100644 --- a/crates/engine/src/cmd/links.rs +++ b/crates/engine/src/cmd/links.rs @@ -2050,6 +2050,36 @@ fn set_found_paths(d: &mut Document, base: LinkBase) { }); } +/// Sets each relative link path of `d`, a document read from `base`, whose file is not found to +/// that path under `base`'s folder, so the link still looks for its file there once the art is +/// placed into a document in another folder. +pub(crate) fn anchor_missing_relative(d: &mut Document, base: LinkBase) { + if base.doc.is_none() { + return; + } + editing_brush_art(d, |d| { + let mut anchored: BTreeMap = BTreeMap::new(); + let mut look = |l: &LinkInfo| { + if Path::new(&l.path).is_relative() + && !anchored.contains_key(&l.path) + && locate(l, base).is_none() + && let Ok(path) = fileio::document_path(&l.path, base.doc) + { + anchored.insert(l.path.clone(), path); + } + }; + d.visit_images(|_, im| im.link.iter().for_each(&mut look)); + d.visit_placed(|_, p| look(&p.link)); + if !anchored.is_empty() { + d.update_links(|l| { + if let Some(path) = anchored.get(&l.path) { + l.path = path.clone(); + } + }); + } + }); +} + /// `d`, a document saved at `doc_path`, as a reply to the caller asking now may show it: without /// read roots in force, `d` itself; with them, a copy in which each link [`path_shown`] does not /// allow names its file alone, without its relative path or the size and date kept of its file, diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 6755da719d..95d48d106a 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -377,7 +377,11 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, given: O )); } // Linked images show their files, found from its folder. - super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false); + let links = super::links::resolve(&mut l.doc, super::links::LinkBase::file(src.path), false, false); + if matches!(format.id, "dxf" | "dwg") { + l.warnings.extend(fileio::dxfimport::missing_image_notes(&links.missing)); + super::links::anchor_missing_relative(&mut l.doc, super::links::LinkBase::file(src.path)); + } (l.doc, l.warnings) }; doc.drop_edit_modes();