From fcf05134a8a87a7fafc94b245a479b6b4fecf7f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 14:20:17 -0800 Subject: [PATCH 01/10] DXF/DWG import: raster images come in as linked images An IMAGE entity was counted as an unknown entity and left out. It now becomes an image linked to the file its IMAGEDEF names, placed on the corner and pixel vectors the entity gives, with its top-left pixel at the top-left. The image takes its size from the entity, else from its IMAGEDEF. A clip boundary (a rectangle or a polygon) makes it a clip group; a boundary that holds the whole image does not. Until the file is read the image shows a placeholder. Opening or placing the drawing finds the file from the drawing's folder, as for other linked images. An image whose file is missing gets a warning and is listed with the document's missing links. Images that name no file, have no size or no area are left out with a warning, and so are inverted clips (the image shows whole) and the brightness, contrast and fade settings. --- crates/cad/src/import.rs | 5 +- crates/cad/src/import/build.rs | 109 +++++- crates/cad/src/import/entity.rs | 76 +++++ crates/cad/src/import/reader.rs | 18 +- crates/cad/src/import/tests_image.rs | 312 ++++++++++++++++++ crates/engine/src/cmd/fileio/dxfimport.rs | 10 + crates/engine/src/cmd/fileio/load.rs | 3 + .../engine/src/cmd/fileio/tests_dxfimport.rs | 83 ++++- crates/engine/src/cmd/place.rs | 5 +- 9 files changed, 615 insertions(+), 6 deletions(-) create mode 100644 crates/cad/src/import/tests_image.rs diff --git a/crates/cad/src/import.rs b/crates/cad/src/import.rs index 5a5582efe1..22918e22ad 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 and solids 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. //! @@ -237,3 +238,5 @@ pub fn import(bytes: &[u8], o: &ImportOptions) -> Result { mod tests; #[cfg(test)] mod tests_dwg; +#[cfg(test)] +mod tests_image; diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 4e1bed4ae1..ce3f8dc0c4 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}; @@ -46,6 +49,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. @@ -314,6 +325,13 @@ 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) => { + 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 +500,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 +609,79 @@ impl<'d, 'a> Build<'d, 'a> { Some(Node::new(self.doc.alloc_id(), NodeKind::Text(Box::new(obj)))) } + /// 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) = im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty()) 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 in document space, unless it shows the whole image. + let clip: Option> = im.clip.as_ref().filter(|c| !covers(c, w, h)).map(|c| c.iter().map(|p| xf * *p).collect()); + let on_canvas = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MAX_EXTENT && p.y.abs() <= MAX_EXTENT; + if clip.as_ref().is_some_and(|c| !c.iter().all(on_canvas)) { + 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) }; + // The clip path and the image are objects of their own (`item` counts the group). + if self.nodes.saturating_add(2) >= MAX_NODES { + self.warn(TOO_MANY); + return None; + } + // Its points, and the close. + let n = clip.len().saturating_add(1); + if self.elements.saturating_add(n) > MAX_ELEMENTS { + self.warn(TOO_MANY_POINTS); + return None; + } + self.nodes += 2; + self.elements += n; + 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 { @@ -704,6 +796,19 @@ 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 { + 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 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 309a4ea228..7a172f9d2e 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -146,6 +146,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 @@ -157,6 +182,7 @@ pub(crate) enum Geom { }, Text(TextItem), Insert(InsertItem), + Image(ImageItem), } /// An entity as art: its geometry and its properties. @@ -182,6 +208,9 @@ const MESHES: &str = "3D polygon meshes and polyface meshes are left out"; 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 INVERTED_CLIPS: &str = "inverted image clips are left out: those images show whole"; impl Converter { fn warn(&mut self, w: &str) { @@ -249,10 +278,35 @@ 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), _ => None, } } + /// An IMAGE (its points are in world coordinates). + fn image(&mut self, im: &model::Image) -> 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); + } + let clip = if !im.clipping { + 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, ocs: Affine) -> Option { if p.is_mesh() || p.is_polyface() { self.warn(MESHES); @@ -347,6 +401,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, } } @@ -370,6 +445,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 f2ed000809..c0dcf0eae4 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; @@ -49,6 +49,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 { @@ -79,6 +88,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, } @@ -112,6 +123,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 }); + } + } for b in doc.blocks { if b.name.is_empty() { continue; diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs new file mode 100644 index 0000000000..75f4af8681 --- /dev/null +++ b/crates/cad/src/import/tests_image.rs @@ -0,0 +1,312 @@ +//! 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_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); +} + +/// 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 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); +} + +/// 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 f152132c69..a64ef07adc 100644 --- a/crates/engine/src/cmd/fileio/load.rs +++ b/crates/engine/src/cmd/fileio/load.rs @@ -915,6 +915,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 524913dcb7..5243b31df9 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}; @@ -241,3 +241,84 @@ 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:?}"); +} diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 9d145853b9..827c4e8243 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -373,7 +373,10 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_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)); + } (l.doc, l.warnings) }; doc.drop_edit_modes(); From d536a46fd9b8a10c8f3652003bfa0a0e2983839a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 14:23:40 -0800 Subject: [PATCH 02/10] DXF/DWG import: check an image clip against the limits before reading it An image's clip boundary was checked against the object and path-point limits only after its points were compared with the image's box, copied and moved into document space. An image with a long boundary placed many times through a block read every point of every copy, even of copies the limits then left out. The limits are now checked first. --- crates/cad/src/import/build.rs | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index ce3f8dc0c4..f2b859ce41 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -633,8 +633,21 @@ impl<'d, 'a> Build<'d, 'a> { if !(xf.as_coeffs().iter().all(|v| v.is_finite()) && xf.determinant() != 0.0) { return None; } - // The clip boundary in document space, unless it shows the whole image. - let clip: Option> = im.clip.as_ref().filter(|c| !covers(c, w, h)).map(|c| c.iter().map(|p| xf * *p).collect()); + // 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. + let clip: Option> = clip.map(|c| c.iter().map(|p| xf * *p).collect()); let on_canvas = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MAX_EXTENT && p.y.abs() <= MAX_EXTENT; if clip.as_ref().is_some_and(|c| !c.iter().all(on_canvas)) { self.warn(FAR_CLIPS); @@ -659,19 +672,8 @@ impl<'d, 'a> Build<'d, 'a> { 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) }; - // The clip path and the image are objects of their own (`item` counts the group). - if self.nodes.saturating_add(2) >= MAX_NODES { - self.warn(TOO_MANY); - return None; - } - // Its points, and the close. - let n = clip.len().saturating_add(1); - if self.elements.saturating_add(n) > MAX_ELEMENTS { - self.warn(TOO_MANY_POINTS); - return None; - } self.nodes += 2; - self.elements += n; + 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) } @@ -799,6 +801,9 @@ 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 { + 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 corner, and each edge along one side: the four corners in order around. From 3280ceffa340de8080d4193f4357839c48cbca08 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 15:31:01 -0800 Subject: [PATCH 03/10] DXF/DWG import: honor an image's clip and transparency flags, keep missing links on Place An IMAGE whose display flags (group 70) leave out Use Clipping Boundary now shows whole even when its clipping state is on. An image whose flags leave out Transparency gets a note that its file's transparency is kept. Placing a drawing in another folder sets each missing relative image link to the drawing's folder, so a later update finds the file once it is put back next to the drawing. --- crates/cad/src/import/entity.rs | 10 +++++-- crates/cad/src/import/tests_image.rs | 27 +++++++++++++++++ .../engine/src/cmd/fileio/tests_dxfimport.rs | 18 +++++++++++ crates/engine/src/cmd/links.rs | 30 +++++++++++++++++++ crates/engine/src/cmd/place.rs | 1 + 5 files changed, 83 insertions(+), 3 deletions(-) diff --git a/crates/cad/src/import/entity.rs b/crates/cad/src/import/entity.rs index dc15db705a..4a566be165 100644 --- a/crates/cad/src/import/entity.rs +++ b/crates/cad/src/import/entity.rs @@ -210,6 +210,7 @@ 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"; impl Converter { @@ -286,13 +287,13 @@ impl Converter { } // 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), + model::EntityKind::Image(im) => self.image(im, g.i(70).is_some()), _ => None, } } /// An IMAGE (its points are in world coordinates). - fn image(&mut self, im: &model::Image) -> Option { + 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) { @@ -302,7 +303,10 @@ impl Converter { if (im.brightness, im.contrast, im.fade) != (50, 50, 0) { self.warn(IMAGE_ADJUSTMENTS); } - let clip = if !im.clipping { + 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); diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index 75f4af8681..83701b85c5 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -131,6 +131,33 @@ fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() { } } +#[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( diff --git a/crates/engine/src/cmd/fileio/tests_dxfimport.rs b/crates/engine/src/cmd/fileio/tests_dxfimport.rs index 5243b31df9..fd2b4d6838 100644 --- a/crates/engine/src/cmd/fileio/tests_dxfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_dxfimport.rs @@ -322,3 +322,21 @@ fn placing_a_drawing_reads_its_images_from_its_folder_and_warns_of_missing_ones( 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 62a84418b0..6ed64fbaec 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 827c4e8243..d5aaf72547 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -376,6 +376,7 @@ fn load_into(p: &Value, cmd: &str, board: Option, link_pdf: bool, slices_o 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) }; From aba54e2ef348d851fa28df2994f621ad941920e8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 15:39:29 -0800 Subject: [PATCH 04/10] DXF/DWG import: a clip boundary that repeats a corner still clips A four-point boundary that visited one corner twice passed the check for a boundary holding the whole image, so the image lost its clip. The check now needs four different corners. --- crates/cad/src/import/build.rs | 4 ++-- crates/cad/src/import/tests_image.rs | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index f2b859ce41..cfe1076f2f 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -801,12 +801,12 @@ 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 { + 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 corner, and each edge along one side: the four corners in order around. + // 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) diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index 83701b85c5..b9c69bc62c 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -131,6 +131,33 @@ fn a_clip_boundary_clips_the_image_and_the_whole_image_s_boundary_does_not() { } } +#[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)] { From 26ced7b8d9e4ceb14b6ea696845e89e55172eeed Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 15:46:32 -0800 Subject: [PATCH 05/10] DXF/DWG import: images left out do not count toward the drawing's bounds An image whose IMAGEDEF is missing or names no file is left out, but its box still counted toward the drawing's bounds, so a far-off image could shrink the rest under Fit or stretch the artboard. Both now use one check for the image's file. --- crates/cad/src/import/build.rs | 8 +++++++- crates/cad/src/import/tests_image.rs | 20 ++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index cfe1076f2f..6275ea99b6 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -326,6 +326,7 @@ impl<'d, 'a> Build<'d, 'a> { 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)); @@ -609,6 +610,11 @@ 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); @@ -621,7 +627,7 @@ impl<'d, 'a> Build<'d, 'a> { /// 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) = im.def.and_then(|h| self.d.images.get(&h)).map(|f| f.path.trim().to_string()).filter(|p| !p.is_empty()) else { + let Some(path) = self.image_file(im) else { self.warn(NO_IMAGE_FILE); return None; }; diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index b9c69bc62c..8c73fe989b 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -242,6 +242,26 @@ fn a_polygon_clip_keeps_its_points_and_an_inverted_clip_shows_the_whole_image_wi 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); From cabe17532ff999cd0596751f7db67e9282d2042f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:00:27 -0800 Subject: [PATCH 06/10] DXF/DWG import: a named block's clipped image is checked where each insert places it A named block becomes a symbol drawn in its own space, without the insert's translation, so an image far out in the block but placed near the origin was left out for clip points that only looked out of range. Image clips in a symbol are now checked for finite values there, and each instance checks the box of its symbol's clips where it lands. A placement whose clips may leave the canvas draws the block's art instead, which leaves out only that image and keeps the block's other art. --- crates/cad/src/import/build.rs | 42 +++++++++++++++++++++++--- crates/cad/src/import/tests_image.rs | 45 ++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 6275ea99b6..806f6c3ec0 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -85,6 +85,12 @@ 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, /// Document space per drawing unit, and its symbols' (no translation). map: Affine, symbol_map: Affine, @@ -148,6 +154,9 @@ 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(), map: Affine::IDENTITY, symbol_map: Affine::IDENTITY, lw_scale: 1.0, @@ -652,10 +661,11 @@ impl<'d, 'a> Build<'d, 'a> { self.warn(TOO_MANY_POINTS); return None; } - // In document space. + // 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 on_canvas = |p: &Point| p.x.is_finite() && p.y.is_finite() && p.x.abs() <= MAX_EXTENT && p.y.abs() <= MAX_EXTENT; - if clip.as_ref().is_some_and(|c| !c.iter().all(on_canvas)) { + let local = self.in_symbol > 0; + let fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && (local || (p.x.abs() <= MAX_EXTENT && p.y.abs() <= MAX_EXTENT)); + if clip.as_ref().is_some_and(|c| !c.iter().all(fits)) { self.warn(FAR_CLIPS); return None; } @@ -678,6 +688,10 @@ impl<'d, 'a> Build<'d, 'a> { 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(); @@ -706,10 +720,23 @@ impl<'d, 'a> Build<'d, 'a> { self.warn(TOO_MANY); break; } + 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 = self.symbol_reach.get(name).map(|r| xf.transform_rect_bbox(*r)); + let leaves = reach.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT)); + if let Some(b) = reach + && self.in_symbol > 0 + { + self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); + } else if leaves { + parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth)); + continue; + } if !self.charge_text(name.len()) { break; } - let xf = map * *cell * self.symbol_map.inverse(); self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) } @@ -773,7 +800,11 @@ impl<'d, 'a> Build<'d, 'a> { } 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(); + self.in_symbol += 1; let art = self.art(name, map, &key.1, depth); + self.in_symbol -= 1; + let reach = std::mem::replace(&mut self.clip_reach, outer); 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. @@ -782,6 +813,9 @@ impl<'d, 'a> Build<'d, 'a> { } 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.doc.symbols.push(Symbol { dynamic: false, name: symbol.clone(), art: Arc::new(art) }); Some(symbol) }); diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index 8c73fe989b..d2d212da04 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -300,6 +300,51 @@ fn an_image_whose_show_image_flag_is_off_is_hidden() { } } +#[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"); +} + #[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 From 5a6086bab4400dbdb60e6cc6e6c66213e3fd509b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 17:35:29 -0800 Subject: [PATCH 07/10] DXF/DWG import: bound a block's clip reach and drop symbols no insert places A block's image clip points are now limited to 4e18 pt from the block's origin, the farthest an insert at the smallest accepted scale (1e-12) still brings back onto the canvas. A clip reach whose placed corners overflow counts as unbounded instead of a box whose NaN sides a union would drop, so every placement of that block draws its art where it lands and checks each clip there. A symbol whose every insert fell back to drawing the block's art is no longer kept in the document with the image link it holds. --- crates/cad/src/import/build.rs | 47 ++++++++++++++++++++++- crates/cad/src/import/tests_image.rs | 56 ++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 806f6c3ec0..d2e3864b5c 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -41,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"; @@ -203,6 +206,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); } @@ -664,7 +668,8 @@ impl<'d, 'a> Build<'d, 'a> { // 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 fits = |p: &Point| p.x.is_finite() && p.y.is_finite() && (local || (p.x.abs() <= MAX_EXTENT && p.y.abs() <= MAX_EXTENT)); + 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; @@ -724,7 +729,7 @@ impl<'d, 'a> Build<'d, 'a> { // 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 = self.symbol_reach.get(name).map(|r| xf.transform_rect_bbox(*r)); + let reach = self.symbol_reach.get(name).map(|r| placed_reach(xf, *r)); let leaves = reach.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT)); if let Some(b) = reach && self.in_symbol > 0 @@ -824,6 +829,44 @@ impl<'d, 'a> Build<'d, 'a> { } } +/// 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), + } +} + +/// 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 /// (`s`: points per drawing unit), measured in the font it is set in. fn fill_span(obj: &mut TextObject, span: Span, s: f64) { diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index d2d212da04..f2bb4d8e7d 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -343,6 +343,62 @@ fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_o 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::>()); +} + +/// 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] From 6073eddb5faa32ba6a106285f2ba70b59490382c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 19:13:17 -0800 Subject: [PATCH 08/10] DXF/DWG import: give back an unused symbol's share of the limits When every placement of a block's symbol draws the block's art because its image clips would leave the canvas, the symbol stayed in the document with its art charged against the object and path-point limits, and the art drawn in its place was charged again. Near the limits, valid lines were left out. Such a placement now takes the art out of a symbol that no instance places yet and gives its share of the limits back, along with the symbols only that art placed. A later placement that needs an instance puts the art back, or draws the symbol again, and charges it again. Symbols still empty at the end are dropped as before. --- crates/cad/src/import/build.rs | 224 ++++++++++++++++++++++++--- crates/cad/src/import/tests_image.rs | 56 +++++++ 2 files changed, 259 insertions(+), 21 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index d2e3864b5c..0b0d74f49d 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -72,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, @@ -94,6 +123,15 @@ pub(crate) struct Build<'d, 'a> { /// 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, @@ -160,6 +198,11 @@ impl<'d, 'a> Build<'d, 'a> { 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, @@ -192,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> { @@ -716,7 +825,10 @@ 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 { @@ -729,19 +841,40 @@ impl<'d, 'a> Build<'d, 'a> { // 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 = self.symbol_reach.get(name).map(|r| placed_reach(xf, *r)); - let leaves = reach.is_some_and(|b| ![b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_EXTENT)); + 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)) { + let back = taken.take().is_some_and(|art| self.restore(name, art)); + if !back && self.symbol(&ins.block, &child, depth, true).is_none() { + continue; + } + if self.nodes >= MAX_NODES { + self.warn(TOO_MANY); + break; + } + reach = reach_of(self); + } if let Some(b) = reach && self.in_symbol > 0 { self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); - } else if leaves { + } else if 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); + } parts.extend(self.art(&ins.block, map * *cell * unbase, &child, depth)); continue; } if !self.charge_text(name.len()) { break; } + *self.uses.entry(name.clone()).or_default() += 1; self.nodes += 1; Some(Node::new(self.doc.alloc_id(), NodeKind::SymbolInstance { symbol: name.clone(), xf })) } @@ -796,37 +929,75 @@ 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 outer = self.clip_reach.take(); - self.in_symbol += 1; - let art = self.art(name, map, &key.1, depth); - self.in_symbol -= 1; - let reach = std::mem::replace(&mut self.clip_reach, outer); - 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 @@ -840,6 +1011,17 @@ pub(crate) fn placed_reach(xf: Affine, r: Rect) -> Rect { } } +/// 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) { diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index f2bb4d8e7d..b2459c7ac7 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -347,6 +347,62 @@ fn a_clipped_image_far_out_in_a_named_block_comes_in_when_its_insert_places_it_o 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`. From d6cc12baf95f87bdd3a8a0babc7f3f051a22253d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 20:29:03 -0800 Subject: [PATCH 09/10] DXF/DWG import: wrap the leaves closure as rustfmt lays it out cargo fmt --all -- --check failed on the long closure line in build.rs. --- crates/cad/src/import/build.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 0b0d74f49d..2ae2ff5f71 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -842,7 +842,8 @@ impl<'d, 'a> Build<'d, 'a> { // 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 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. From ad1a7bf8664ed619a0efb260d7e45907a2b8456b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 4 Dec 2026 21:36:15 -0800 Subject: [PATCH 10/10] DXF/DWG import: an insert drawn as art gets back its symbol's objects at the limit The object limit was checked at the start of each insert copy, before the copy could take out its unused symbol and draw the block's art in that room, so a copy whose image clip leaves the canvas lost its art when building the symbol had used the last objects. The limit is now checked after that, and before an empty symbol is drawn again or a copy is drawn as art, so copies past the limit stop without looking at the block. A nested instance's clip box joins the enclosing symbol's only once the instance is kept. The tests use a 100,000-object limit. --- crates/cad/src/import/build.rs | 35 ++++++++----- crates/cad/src/import/tests_image.rs | 77 ++++++++++++++++++++++++++++ 2 files changed, 98 insertions(+), 14 deletions(-) diff --git a/crates/cad/src/import/build.rs b/crates/cad/src/import/build.rs index 2ae2ff5f71..0ebe26f12e 100644 --- a/crates/cad/src/import/build.rs +++ b/crates/cad/src/import/build.rs @@ -25,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 }; @@ -833,10 +833,6 @@ impl<'d, 'a> Build<'d, 'a> { for cell in &ins.cells { let node = match &symbol { Some(name) => { - if self.nodes >= MAX_NODES { - self.warn(TOO_MANY); - break; - } 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 @@ -848,33 +844,44 @@ impl<'d, 'a> Build<'d, 'a> { // 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)) { - let back = taken.take().is_some_and(|art| self.restore(name, art)); - if !back && self.symbol(&ins.block, &child, depth, true).is_none() { - continue; - } 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); } - if let Some(b) = reach - && self.in_symbol > 0 - { - self.clip_reach = Some(self.clip_reach.map_or(b, |r| r.union(b))); - } else if leaves(reach) { + // 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; + } if !self.charge_text(name.len()) { break; } + 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 })) diff --git a/crates/cad/src/import/tests_image.rs b/crates/cad/src/import/tests_image.rs index b2459c7ac7..9d85ca08ba 100644 --- a/crates/cad/src/import/tests_image.rs +++ b/crates/cad/src/import/tests_image.rs @@ -477,6 +477,83 @@ fn clip_paths_count_against_the_path_point_limit() { 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(