diff --git a/crates/midra-layout/src/import.rs b/crates/midra-layout/src/import.rs index dff0065..31c7261 100644 --- a/crates/midra-layout/src/import.rs +++ b/crates/midra-layout/src/import.rs @@ -44,6 +44,14 @@ pub struct ImportDocument { pub svg: bool, pub note: String, } +fn xml_options() -> roxmltree::ParsingOptions { + roxmltree::ParsingOptions { + // Draw.io Desktop emits the standard SVG 1.1 public DOCTYPE. Roxmltree + // never fetches its external identifier and limits entity expansion. + allow_dtd: true, + nodes_limit: 200_000, + } +} pub fn parse_values(text: &str) -> Result { if text.len() > crate::exchange::MAX_EXCHANGE_BYTES { return Err("Import text exceeds 16 MiB.".into()); @@ -52,7 +60,8 @@ pub fn parse_values(text: &str) -> Result { return parse_midra_values(text); } if text.trim_start().starts_with('<') - && roxmltree::Document::parse(text).is_ok_and(|d| d.root_element().has_tag_name("svg")) + && roxmltree::Document::parse_with_options(text, xml_options()) + .is_ok_and(|d| d.root_element().has_tag_name("svg")) { return parse_svg(text); } @@ -477,11 +486,113 @@ fn walk( } Ok(()) } + +/// Draw.io Desktop's SVG exporter keeps the source cell ID on a wrapper group, +/// but turns image cells into `/` and adds HTML/raster label +/// fallbacks. Read one geometry primitive from each cell instead of treating +/// those rendering details as independent layer rectangles. +fn drawio_svg_shapes( + root: Node, + matrix: Matrix, + viewport: [f64; 2], +) -> Result>, String> { + let has_root_cells = root + .descendants() + .any(|n| n.attribute("data-cell-id") == Some("0")) + && root + .descendants() + .any(|n| n.attribute("data-cell-id") == Some("1")); + if !has_root_cells { + return Ok(None); + } + let mut out = Vec::new(); + for cell in root.descendants().filter(|n| { + n.is_element() + && n.attribute("data-cell-id") + .is_some_and(|id| !matches!(id, "0" | "1")) + }) { + let id = cell.attribute("data-cell-id").unwrap(); + if out.iter().any(|shape: &DetectedShape| shape.id == id) { + return Err(format!("Duplicate draw.io SVG cell ID: {id}.")); + } + let primitive = cell + .descendants() + .find(|n| n.is_element() && matches!(n.tag_name().name(), "rect" | "image" | "use")) + .ok_or_else(|| { + format!( + "Draw.io SVG cell {id} is not a rectangle or image. Export axis-aligned layer boxes." + ) + })?; + let dim = |name: &str, default: Option<&str>, axis: usize| { + length( + primitive + .attribute(name) + .or(default) + .ok_or_else(|| format!("Missing SVG {name} in draw.io cell {id}."))?, + Some(viewport[axis]), + ) + }; + if primitive.has_tag_name("rect") + && (dim("rx", Some("0"), 0)? != 0.0 || dim("ry", Some("0"), 1)? != 0.0) + { + return Err(format!( + "Draw.io SVG cell {id} is rounded; export square layer boxes." + )); + } + let raw = Geometry { + x: dim("x", Some("0"), 0)?, + y: dim("y", Some("0"), 1)?, + width: dim("width", None, 0)?, + height: dim("height", None, 1)?, + } + .validate()?; + let mut cell_matrix = matrix; + let mut ancestors: Vec<_> = primitive + .ancestors() + .take_while(|node| *node != root) + .filter(|node| node.is_element()) + .collect(); + ancestors.reverse(); + for ancestor in ancestors { + cell_matrix = cell_matrix.nested(ancestor)?; + } + cell_matrix = cell_matrix.nested(primitive)?; + let geometry = cell_matrix.bounds(raw)?; + let stroke = if inherited(primitive, "stroke").is_none_or(|v| v == "none") + || inherited(primitive, "stroke-opacity") == Some("0") + { + 0.0 + } else { + length(inherited(primitive, "stroke-width").unwrap_or("1"), None)? + }; + if stroke < 0.0 { + return Err("SVG stroke width cannot be negative.".into()); + } + let background = id == "midra-background"; + out.push(DetectedShape { + id: id.to_owned(), + geometry, + outline: [stroke * cell_matrix.x.abs(), stroke * cell_matrix.y.abs()], + background, + background_only: background, + zoom: None, + }); + if out.iter().filter(|shape| !shape.background_only).count() > 256 || out.len() > 257 { + return Err("Import is limited to 256 rectangles.".into()); + } + } + if out.is_empty() { + return Err("No layer cells detected in draw.io SVG.".into()); + } + Ok(Some(out)) +} + pub fn parse_svg(text: &str) -> Result { if text.len() > crate::exchange::MAX_EXCHANGE_BYTES { return Err("SVG exceeds 16 MiB.".into()); } - let document = roxmltree::Document::parse(text).map_err(|e| format!("Invalid SVG XML: {e}"))?; + let document = roxmltree::Document::parse_with_options(text, xml_options()) + .map_err(|e| format!("Invalid SVG XML: {e}"))?; let root = document.root_element(); if let Some(version) = root.attribute("data-midra-layout-geometry") && !matches!(version, "1" | "2") @@ -559,8 +670,14 @@ pub fn parse_svg(text: &str) -> Result { return Err("SVG preserveAspectRatio currently supports xMidYMid meet or none. Other alignments/cropping must be flattened first.".into()); } } + let drawio_svg = drawio_svg_shapes(root, matrix, viewport)?; + let rendered_by_drawio = drawio_svg.is_some(); let mut shapes = Vec::new(); - walk(root, matrix, viewport, page, &mut shapes, 0)?; + if let Some(imported) = drawio_svg { + shapes = imported; + } else { + walk(root, matrix, viewport, page, &mut shapes, 0)?; + } if shapes.is_empty() { return Err("No visible rectangles detected in SVG.".into()); } @@ -568,7 +685,12 @@ pub fn parse_svg(text: &str) -> Result { shapes, svg: true, note: format!( - "SVG page: {} × {} px. CSS units use 96 px/in; viewBox and axis-aligned transforms are applied. Coordinates are relative to this SVG page; copying/exporting only a selection may lose the original document position.", + "{}SVG page: {} × {} px. CSS units use 96 px/in; viewBox and axis-aligned transforms are applied. Coordinates are relative to this SVG page; draw.io may crop and rebase exports without a background.", + if rendered_by_drawio { + "Draw.io-rendered " + } else { + "" + }, crate::view_pixels(page[0]), crate::view_pixels(page[1]) ), diff --git a/crates/midra-layout/tests/import.rs b/crates/midra-layout/tests/import.rs index 8f83cba..c88de86 100644 --- a/crates/midra-layout/tests/import.rs +++ b/crates/midra-layout/tests/import.rs @@ -102,6 +102,44 @@ fn rectangular_paths_polygons_hidden_nodes_and_image_background_are_handled() { .unwrap(); assert_eq!(d.shapes.len(), 1); } + +#[test] +fn drawio_rendered_svg_uses_cell_geometry_and_ignores_label_fallbacks() { + let rendered = r##" + + + + + + + + + + + Text is not SVG +"##; + let doc = parse_svg(rendered).unwrap(); + assert_eq!(parse_values(rendered).unwrap().shapes.len(), 3); + assert!(doc.note.starts_with("Draw.io-rendered SVG page:")); + assert_eq!(doc.shapes.len(), 3); + assert_eq!(doc.shapes[0].id, "midra-background"); + assert!(doc.shapes[0].background_only); + assert_eq!(doc.shapes[1].id, "layer-2"); + assert_eq!( + doc.shapes[1].geometry, + Geometry { + x: 120.0, + y: 180.0, + width: 640.0, + height: 360.0, + } + ); + assert_eq!(doc.shapes[2].id, "layer-1"); + assert_eq!(doc.shapes[2].geometry.x, 1160.0); + assert_eq!(doc.shapes[2].geometry.y, 180.0); +} + #[test] fn unsupported_or_ambiguous_svg_is_refused_without_partial_shapes() { for body in [ diff --git a/docs/interfaces/midra-layout-exchange.md b/docs/interfaces/midra-layout-exchange.md index ea1b255..436abe7 100644 --- a/docs/interfaces/midra-layout-exchange.md +++ b/docs/interfaces/midra-layout-exchange.md @@ -103,6 +103,20 @@ screen resolution is not imported. Mapped names, sources and Midra links stay wi the destination layers. File replacement retains the existing explicit overwrite confirmation and atomic-write path. +SVG files rendered by draw.io Desktop are also accepted. The importer recognizes +the `data-cell-id` wrapper groups retained by draw.io, reads the first rectangle, +image or symbol use in each cell, and ignores generated HTML labels, raster text +fallbacks, symbols and the draw.io help link. The standard SVG 1.1 public DOCTYPE +emitted by draw.io is accepted without fetching external content; XML parsing is +limited to 200,000 nodes. The reserved `midra-background` cell remains an ignored +background. + +Draw.io's SVG export normally crops the canvas to the diagram content, adds one +pixel to its bounds and rebases cell coordinates. Those rebased coordinates are +the only positions present in that SVG. Include Midra Layout's background layer +before exporting through draw.io when the full output-screen origin must survive +the round trip. + Tests cover each format/artwork combination, full-screen layers vs backgrounds, negative/fractional coordinates, repeat round trips, compressed clipboard/files, embedded references, invalid IDs/versions and no-overwrite file handling. @@ -112,12 +126,16 @@ A manual native-editor check is available: cargo run --locked -p midra-layout --example check_geometry_exchange -- generate /tmp/midra-exchange-check drawio -x --size page -o /tmp/midra-exchange-check/render.png /tmp/midra-exchange-check/illustrated.drawio drawio -x -o /tmp/midra-exchange-check/resaved.xml /tmp/midra-exchange-check/illustrated.drawio +drawio -x -f svg -o /tmp/midra-exchange-check/drawio-rendered.svg /tmp/midra-exchange-check/illustrated.drawio cargo run --locked -p midra-layout --example check_geometry_exchange -- verify /tmp/midra-exchange-check/resaved.xml +cargo run --locked -p midra-layout --example check_geometry_exchange -- verify /tmp/midra-exchange-check/drawio-rendered.svg ``` On 2026-11-14, installed **draw.io Desktop 31.7.0** (`/usr/bin/drawio`, not Flatpak) rendered the illustrated diagram correctly, and its re-saved XML returned both -layer boxes unchanged. Generated plain/illustrated SVG and draw.io files also +layer boxes unchanged. Its SVG export, including `/` image cells and +HTML/raster label fallbacks, also returned both layer boxes unchanged when the +background preserved the page. Generated plain/illustrated SVG and draw.io files passed geometry verification. Native output artifacts remain in `/tmp`, not Git. Protocol references: [draw.io diagram format](https://www.drawio.com/docs/reference/diagram-generation/) diff --git a/docs/midra-layout.md b/docs/midra-layout.md index e08c00d..be54c2a 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -562,7 +562,10 @@ cropping). Images are embedded and require no external files. Import either format with **Import → SVG / draw.io file…** or paste its XML, then map detected layers to destinations. Backgrounds are automatically ignored; placeholder images each count as one layer. draw.io files saved with compression -are supported. These exports round-trip whole-pixel visible-box geometry, not +are supported. SVG rendered by draw.io Desktop is recognized through its retained +cell IDs; generated HTML labels and raster text fallbacks are ignored. Draw.io +may crop and rebase that SVG unless the exported diagram includes the background +layer. These exports round-trip whole-pixel visible-box geometry, not source/crop settings; JSON preserves the full project. See the [geometry exchange contract and native draw.io checks](interfaces/midra-layout-exchange.md) and [project save contract](interfaces/midra-layout.md). diff --git a/docs/midralayout/changelog.md b/docs/midralayout/changelog.md index 5cd8d26..8ca5083 100644 --- a/docs/midralayout/changelog.md +++ b/docs/midralayout/changelog.md @@ -4,6 +4,8 @@ ## Unreleased +- Import SVG rendered by draw.io Desktop, including its SVG 1.1 DOCTYPE, nested cell wrappers, symbol/image layers and generated label fallbacks. A background-preserved native 31.7.0 round trip was checked; draw.io's cropped SVG exports necessarily retain their rebased coordinates. + - Add current-layer SVG and draw.io exports with optional embedded backgrounds and source-pattern placeholders; import native/compressed draw.io files. Round-trip tests cover scopes/artwork and whole-pixel geometry; draw.io Desktop 31.7.0 rendering and XML re-save were checked. Use JSON for full source/crop fidelity. - Hide tiled source patterns outside crop editing, even with saved pattern display enabled. Double-click/Crop properties reveals the selected layer’s pattern; the existing preference now shows other layers’ patterns only while cropping.