diff --git a/Cargo.lock b/Cargo.lock index 8321e1e..f95cabc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2399,6 +2399,7 @@ dependencies = [ "image", "rfd", "roxmltree", + "svgtypes", ] [[package]] diff --git a/crates/midra-layout/Cargo.toml b/crates/midra-layout/Cargo.toml index 6ce9a4a..3b979ec 100644 --- a/crates/midra-layout/Cargo.toml +++ b/crates/midra-layout/Cargo.toml @@ -11,3 +11,4 @@ roxmltree = "0.20" eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "x11", "wayland"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp"] } rfd = "0.15" +svgtypes = "0.15" diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index 4651ad0..eee1ada 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -2,9 +2,8 @@ use super::*; #[path = "format_ui.rs"] mod format_ui; use format_ui::{FormatDraft, OutputDraft}; -use midra_layout::{ - AlignTarget, Alignment, Corner, DrawioShape, Geometry, Layout, ResizeHandle, parse_drawio, -}; +use midra_layout::import::{DetectedShape, ImportDocument, parse_svg, parse_values}; +use midra_layout::{AlignTarget, Alignment, Corner, Geometry, Layout, ResizeHandle}; pub struct Editor { layout: Layout, @@ -35,28 +34,90 @@ struct Marquee { previous: [bool; 2], } struct Paste { - target: usize, + targets: Vec, text: String, - shapes: Vec, - choice: usize, + shapes: Vec, + mapping: Vec>, + ignored: Vec, + svg: bool, + note: String, include_size: bool, include_outline: bool, error: String, } impl Paste { + fn set_document(&mut self, doc: ImportDocument) { + self.shapes = doc.shapes; + self.svg = doc.svg; + self.note = doc.note; + self.ignored = vec![false; self.shapes.len()]; + self.reset_mapping(); + self.error.clear(); + } + fn reset_mapping(&mut self) { + let mut targets = self.targets.iter(); + self.mapping = self + .ignored + .iter() + .map(|ignored| { + if *ignored { + None + } else { + targets.next().copied() + } + }) + .collect(); + } fn parse(&mut self) { - self.choice = 0; - match parse_drawio(&self.text) { - Ok(shapes) => { - self.shapes = shapes; - self.error.clear(); - } - Err(error) => { + match parse_values(&self.text) { + Ok(doc) => self.set_document(doc), + Err(e) => { self.shapes.clear(); - self.error = error; + self.mapping.clear(); + self.ignored.clear(); + self.error = e; } } } + fn values(&self, layout: &Layout) -> Result, String> { + let count = self.ignored.iter().filter(|v| !**v).count(); + if count != self.targets.len() { + return Err(format!( + "Layer count mismatch: {} selected, {} detected ({} excluded). Select {} destination layer(s), or supply {} rectangle(s).", + self.targets.len(), + count, + self.shapes.len() - count, + count, + self.targets.len() + )); + } + if layout.selected_indices() != self.targets { + return Err( + "Selection changed. Close this review and import again for the current selection." + .into(), + ); + } + let mut values = Vec::new(); + for (row, shape) in self.shapes.iter().enumerate() { + if self.ignored[row] { + continue; + } + let target = + self.mapping[row].ok_or("Choose a destination for each detected rectangle.")?; + if !self.targets.contains(&target) || values.iter().any(|(i, _)| *i == target) { + return Err("Each selected layer must be mapped exactly once; choose a different destination for duplicate mappings.".into()); + } + values.push(( + target, + shape.paste_geometry( + layout.layers()[target], + self.include_size, + self.include_outline, + )?, + )); + } + Ok(values) + } } impl Default for Editor { fn default() -> Self { @@ -184,22 +245,62 @@ impl Editor { } } fn open_paste(&mut self, text: String) { - if let Some(target) = self.layout.selected() { - let mut p = Paste { - target, - text, - shapes: Vec::new(), - choice: 0, - include_size: true, - include_outline: false, - error: String::new(), - }; - if !p.text.is_empty() { - p.parse(); + let targets = self.layout.selected_indices(); + if targets.is_empty() { + self.error = "Select one or more destination layers before importing values.".into(); + return; + } + let mut p = Paste { + targets, + text, + shapes: Vec::new(), + mapping: Vec::new(), + ignored: Vec::new(), + svg: false, + note: String::new(), + include_size: true, + include_outline: false, + error: String::new(), + }; + if !p.text.is_empty() { + p.parse(); + } + self.paste = Some(p); + } + fn import_svg_file(&mut self) { + if self.layout.selected_indices().is_empty() { + self.error = "Select one or more destination layers before importing SVG.".into(); + return; + } + if let Some(path) = rfd::FileDialog::new() + .add_filter("SVG", &["svg"]) + .pick_file() + { + self.open_paste(String::new()); + if let Some(p) = self.paste.as_mut() { + Self::read_svg(&path, p); + } + } + } + fn read_svg(path: &std::path::Path, p: &mut Paste) { + use std::io::Read; + let result = (|| { + let mut text = String::new(); + std::fs::File::open(path) + .map_err(|e| format!("Cannot open SVG: {e}"))? + .take(1_048_577) + .read_to_string(&mut text) + .map_err(|e| format!("Cannot read SVG: {e}"))?; + let doc = parse_svg(&text)?; + p.text = text; + Ok(doc) + })(); + match result { + Ok(doc) => p.set_document(doc), + Err(e) => { + p.shapes.clear(); + p.error = e; } - self.paste = Some(p); - } else { - self.error = "Select exactly one layer before pasting.".into(); } } fn apply_fields(&mut self) { @@ -385,100 +486,60 @@ impl Editor { return; }; let mut close = false; - let response = egui::Modal::new(egui::Id::new("drawio-paste")).show(ctx, |ui| { - ui.set_width(530.0); - ui.heading("Paste draw.io geometry"); - ui.label(format!("Target: {}", label(p.target))); - ui.label("1 draw.io unit = 1 screen pixel · top-left origin"); - ui.label("Paste encoded clipboard text or raw mxGraphModel XML:"); - if ui - .add( - egui::TextEdit::multiline(&mut p.text) - .desired_rows(4) - .desired_width(f32::INFINITY), - ) - .changed() - { - p.shapes.clear(); - p.error.clear(); - } - if ui.button("Read geometry").clicked() { - p.parse(); - } - if !p.error.is_empty() { - ui.colored_label(AMBER, &p.error); - } - if !p.shapes.is_empty() { - if p.shapes.len() > 1 { - egui::ComboBox::from_label("Rectangle") - .selected_text(&p.shapes[p.choice].id) - .show_ui(ui, |ui| { - for (i, s) in p.shapes.iter().enumerate() { - ui.selectable_value( - &mut p.choice, - i, - format!( - "Cell {} · {} × {}", - s.id, s.geometry.width, s.geometry.height - ), - ); - } - }); - } - ui.checkbox( - &mut p.include_size, - "Include size / format (otherwise position only)", - ); - let shape = &p.shapes[p.choice]; - ui.add_enabled( - p.include_size && shape.stroke_width > 0.0, - egui::Checkbox::new(&mut p.include_outline, "Include outline in bounds"), - ); - if !p.include_size { - ui.small("Outline adjustment requires size import; position-only uses the original top-left."); - } else if shape.stroke_width == 0.0 { - ui.small("No visible outline to include."); - } else { - ui.small(format!("Outline: {} px · extends {} px beyond each edge. Center stays unchanged.", number(shape.stroke_width), number(shape.stroke_width / 2.0))); - } - let before = self.layout.layers()[p.target]; - match shape.paste_geometry(before, p.include_size, p.include_outline) { - Ok(after) => { - ui.separator(); - ui.columns(2, |cols| { - cols[0].label("Before"); - cols[0].label(bounds(before)); - cols[1].label("After"); - cols[1].label(bounds(after)); - }); - if after.outside_on(self.layout.formats().output) { - ui.colored_label( - AMBER, - "This rectangle extends outside the screen. Its coordinates are preserved.", - ); + let response=egui::Modal::new(egui::Id::new("layer-values-import")).show(ctx,|ui| { + ui.set_width(600.0); + ui.heading("Paste layer(s) values"); + ui.label(format!("Selected destinations: {}",p.targets.iter().map(|i|label(*i)).collect::>().join(", "))); + ui.label("Paste draw.io clipboard data or SVG XML, or import an SVG file."); + egui::ScrollArea::vertical().max_height((ctx.screen_rect().height()-360.0).max(150.0)).show(ui,|ui| { + if ui.add(egui::TextEdit::multiline(&mut p.text).desired_rows(3).desired_width(f32::INFINITY)).changed() {p.shapes.clear();p.error.clear();} + ui.horizontal(|ui| { + if ui.button("Read geometry").clicked() {p.parse();} + if ui.button("Import SVG…").clicked() && let Some(path)=rfd::FileDialog::new().add_filter("SVG", &["svg"]).pick_file() {Self::read_svg(&path,&mut p);} + }); + if !p.error.is_empty() {ui.colored_label(AMBER,&p.error);} + if p.shapes.is_empty() {return;} + ui.label(&p.note); + ui.checkbox(&mut p.include_size,"Include size / format (otherwise position only)"); + ui.add_enabled(p.include_size && p.shapes.iter().any(|s|s.outline.iter().any(|v|*v>0.0)),egui::Checkbox::new(&mut p.include_outline,"Include outline in bounds")); + ui.small("Bounds only; source format, colors and outline appearance are not imported."); + if !p.include_size {ui.small("Position-only uses the original top-left; outline adjustment requires size import.");} + ui.separator(); + ui.strong("Detected rectangles / destination layers"); + let mut reset_mapping=false; + for (row,shape) in p.shapes.iter().enumerate() { + ui.push_id(row,|ui| { + ui.label(format!("{} · {}",row+1,shape.id)); + ui.small(bounds(shape.geometry)); + if p.svg && shape.background { + reset_mapping|=ui.checkbox(&mut p.ignored[row],"Ignore full-page background").changed(); } - ui.label("Bounds only; source format, colors and outline appearance are not imported."); - if ui - .add(egui::Button::new("Apply to selected target").fill(PURPLE)) - .clicked() - { - match self.layout.apply(p.target, after) { - Ok(()) => { - self.sync(); - close = true; + if !p.ignored[row] { + egui::ComboBox::from_id_salt("destination").selected_text(p.mapping[row].map(label).unwrap_or("Choose destination…")).show_ui(ui,|ui| { + for target in &p.targets {ui.selectable_value(&mut p.mapping[row],Some(*target),label(*target));} + }); + if let Some(target)=p.mapping[row] { + let before=self.layout.layers()[target]; + if let Ok(after)=shape.paste_geometry(before,p.include_size,p.include_outline) { + ui.columns(2,|cols| {cols[0].label("Before");cols[0].small(bounds(before));cols[1].label("After");cols[1].small(bounds(after));}); + if after.outside_on(self.layout.formats().output) {ui.colored_label(AMBER,"Outside the screen; imported coordinates will be preserved.");} } - Err(e) => p.error = e, } } - } - Err(error) => { - ui.colored_label(AMBER, error); - } + ui.separator(); + }); + } + if reset_mapping {p.reset_mapping();} + }); + if !p.shapes.is_empty() { + let values=p.values(&self.layout); + let valid=values.as_ref().map_err(Clone::clone).and_then(|values| {let mut preview=self.layout.clone();preview.apply_import(values)}); + if let Err(e)=&valid {ui.colored_label(AMBER,e);} + if ui.add_enabled(valid.is_ok(),egui::Button::new("Apply mapped values").fill(PURPLE)).clicked() && let Ok(values)=values { + match self.layout.apply_import(&values) {Ok(())=>{self.sync();close=true;},Err(e)=>p.error=e} } } - if ui.button("Cancel").clicked() { - close = true; - } + if ui.button("Cancel").clicked() {close=true;} }); if !close && !response.should_close() { self.paste = Some(p); @@ -730,7 +791,7 @@ impl Editor { if click(ui, &ink, [0.0, 780.0, w, 34.0], "copy-values") { self.copy(ui.ctx()); } - ink.button(0.0, 829.0, w, "Paste draw.io…", false); + ink.button(0.0, 829.0, w, "Paste layer(s) values", false); if click(ui, &ink, [0.0, 829.0, w, 34.0], "paste-button") { self.open_paste(String::new()); } @@ -813,7 +874,7 @@ impl Editor { ink.text( 0.0, 849.0, - "Select one layer to edit its size or paste.", + "Select one layer to edit its size; paste accepts the full selection.", 12.0, MUTED, ); @@ -890,7 +951,7 @@ impl Editor { } } } - ink.button(438.0, 67.0, 154.0, "Paste draw.io…", true); + ink.button(438.0, 67.0, 154.0, "Paste layer(s) values", true); if click(ui, &ink, [438.0, 67.0, 154.0, 34.0], "toolbar-paste") { self.open_paste(String::new()); } @@ -932,8 +993,12 @@ impl Editor { MUTED, ) }; + ink.button(24.0, 142.0, 154.0, "Import SVG…", false); + if click(ui, &ink, [24.0, 142.0, 154.0, 34.0], "import-svg") { + self.import_svg_file(); + } ui.put( - Rect::from_min_size(ink.point(25.0, 129.0), Vec2::new(r.width() - 50.0, 58.0)), + Rect::from_min_size(ink.point(190.0, 129.0), Vec2::new(r.width() - 215.0, 58.0)), egui::Label::new(egui::RichText::new(text).color(color)).wrap(), ); let area = Rect::from_min_max( @@ -1651,13 +1716,57 @@ mod tests { ); assert_eq!(*app.layout.layers(), before); let p = app.paste.as_ref().unwrap(); - assert_eq!(p.target, 1); + assert_eq!(p.targets, vec![1]); assert_eq!(p.shapes[0].geometry.width, 945.0); frame(&mut app, &ctx, vec![key(egui::Key::Escape)]); assert!(app.paste.is_none()); assert_eq!(*app.layout.layers(), before); } #[test] + fn import_review_excludes_background_and_applies_reversed_mapping_atomically() { + let mut app = Editor::default(); + let ctx = egui::Context::default(); + app.layout.set_selection([true; 2]); + let before = *app.layout.layers(); + app.open_paste(r#""#.into()); + let p = app.paste.as_mut().unwrap(); + assert!( + p.values(&app.layout) + .unwrap_err() + .contains("2 selected, 3 detected") + ); + p.ignored[0] = true; + p.reset_mapping(); + p.mapping[1] = Some(1); + p.mapping[2] = Some(1); + assert!(p.values(&app.layout).is_err()); + p.mapping[2] = Some(0); + let expected = [p.shapes[2].geometry, p.shapes[1].geometry]; + assert_eq!(*app.layout.layers(), before); + frame(&mut app, &ctx, vec![]); + let output = frame(&mut app, &ctx, vec![]); + let pos = output + .shapes + .iter() + .find_map(|s| match &s.shape { + egui::epaint::Shape::Text(t) if t.galley.job.text == "Apply mapped values" => { + Some(t.pos + Vec2::new(20.0, 6.0)) + } + _ => None, + }) + .unwrap(); + frame( + &mut app, + &ctx, + vec![egui::Event::PointerMoved(pos), mouse(pos, true)], + ); + frame(&mut app, &ctx, vec![mouse(pos, false)]); + assert!(app.paste.is_none()); + assert_eq!(*app.layout.layers(), expected); + app.layout.undo(); + assert_eq!(*app.layout.layers(), before); + } + #[test] fn numeric_focus_keeps_paste_out_of_importer_and_arrows_out_of_geometry() { let mut app = Editor::default(); let ctx = egui::Context::default(); @@ -1729,7 +1838,7 @@ mod tests { .shapes .iter() .find_map(|s| match &s.shape { - egui::epaint::Shape::Text(t) if t.galley.job.text == "Apply to selected target" => { + egui::epaint::Shape::Text(t) if t.galley.job.text == "Apply mapped values" => { Some(t.pos + Vec2::new(30.0, 6.0)) } _ => None, @@ -1789,7 +1898,7 @@ mod tests { include_str!("../tests/fixtures/drawio-rectangle.txt").into(), )], ); - assert_eq!(app.paste.as_ref().unwrap().target, 0); + assert_eq!(app.paste.as_ref().unwrap().targets, vec![0]); } #[test] fn zoom_changes_camera_without_geometry_or_undo_edits() { @@ -1828,7 +1937,7 @@ mod tests { )], ); assert!(!app.paste.as_ref().unwrap().include_outline); - for text in ["Include outline in bounds", "Apply to selected target"] { + for text in ["Include outline in bounds", "Apply mapped values"] { let output = frame(&mut app, &ctx, vec![]); let pos = output .shapes @@ -2123,7 +2232,12 @@ mod tests { app.layout.undo(); assert_eq!(*app.layout.layers(), before); app.open_paste(include_str!("../tests/fixtures/drawio-rectangle.txt").into()); - assert!(app.paste.is_none()); - assert!(app.error.contains("exactly one")); + let paste = app.paste.as_ref().unwrap(); + assert!( + paste + .values(&app.layout) + .unwrap_err() + .contains("Layer count mismatch") + ); } } diff --git a/crates/midra-layout/src/import.rs b/crates/midra-layout/src/import.rs new file mode 100644 index 0000000..787284f --- /dev/null +++ b/crates/midra-layout/src/import.rs @@ -0,0 +1,467 @@ +//! Bounds-only imports. SVG is parsed locally; external content is never fetched. +use crate::{Geometry, parse_drawio}; +use roxmltree::Node; +use std::str::FromStr; + +#[derive(Clone, Debug)] +pub struct DetectedShape { + pub id: String, + pub geometry: Geometry, + pub outline: [f64; 2], + pub background: bool, + pub background_only: bool, +} +impl DetectedShape { + pub fn paste_geometry( + &self, + before: Geometry, + size: bool, + outline: bool, + ) -> Result { + if self.background_only { + return Err( + "Ignore the background image; image content cannot be imported as layer values." + .into(), + ); + } + let mut g = self.geometry; + if !size { + g.width = before.width; + g.height = before.height; + } else if outline { + g.x -= self.outline[0] / 2.0; + g.y -= self.outline[1] / 2.0; + g.width += self.outline[0]; + g.height += self.outline[1]; + } + g.validate() + } +} +#[derive(Clone, Debug)] +pub struct ImportDocument { + pub shapes: Vec, + pub svg: bool, + pub note: String, +} +pub fn parse_values(text: &str) -> Result { + if text.len() > 1_048_576 { + return Err("Import text exceeds 1 MiB.".into()); + } + if text.trim_start().starts_with('<') + && roxmltree::Document::parse(text).is_ok_and(|d| d.root_element().has_tag_name("svg")) + { + return parse_svg(text); + } + Ok(ImportDocument { + shapes: parse_drawio(text)? + .into_iter() + .map(|s| DetectedShape { + id: s.id, + geometry: s.geometry, + outline: [s.stroke_width; 2], + background: false, + background_only: false, + }) + .collect(), + svg: false, + note: "Draw.io: 1 diagram unit = 1 output pixel; original top-left coordinates retained." + .into(), + }) +} +#[derive(Clone, Copy)] +struct Matrix { + x: f64, + y: f64, + tx: f64, + ty: f64, +} +impl Matrix { + fn nested(self, n: Node) -> Result { + let local = n.attribute("transform").unwrap_or(""); + let t = svgtypes::Transform::from_str(local) + .map_err(|e| format!("Invalid SVG transform: {e}"))?; + if [t.a, t.b, t.c, t.d, t.e, t.f] + .iter() + .any(|v| !v.is_finite()) + || t.b.abs() > 1e-10 + || t.c.abs() > 1e-10 + || t.a == 0.0 + || t.d == 0.0 + { + return Err("SVG rotation, skew and collapsed transforms are unsupported. Use axis-aligned rectangles.".into()); + } + Ok(Self { + x: self.x * t.a, + y: self.y * t.d, + tx: self.tx + self.x * t.e, + ty: self.ty + self.y * t.f, + }) + } + fn bounds(self, g: Geometry) -> Result { + let x = [self.tx + self.x * g.x, self.tx + self.x * (g.x + g.width)]; + let y = [self.ty + self.y * g.y, self.ty + self.y * (g.y + g.height)]; + Geometry { + x: x[0].min(x[1]), + y: y[0].min(y[1]), + width: (x[1] - x[0]).abs(), + height: (y[1] - y[0]).abs(), + } + .validate() + } +} +fn length(text: &str, percent: Option) -> Result { + let value = + svgtypes::Length::from_str(text).map_err(|e| format!("Invalid SVG length {text}: {e}"))?; + use svgtypes::LengthUnit::*; + let factor = match value.unit { + None | Px => 1.0, + In => 96.0, + Cm => 96.0 / 2.54, + Mm => 96.0 / 25.4, + Pt => 96.0 / 72.0, + Pc => 16.0, + Percent => { + percent.ok_or("SVG root percentage dimensions need an explicit pixel size.")? / 100.0 + } + _ => return Err("Font-relative SVG lengths are unsupported.".into()), + }; + let result = value.number * factor; + if !result.is_finite() { + return Err("SVG dimensions must be finite.".into()); + } + Ok(result) +} +fn property<'a>(node: Node<'a, '_>, name: &str) -> Option<&'a str> { + node.attribute("style") + .and_then(|s| { + s.split(';') + .filter_map(|part| part.split_once(':')) + .filter(|(key, _)| key.trim() == name) + .map(|(_, v)| v.trim()) + .next_back() + }) + .or_else(|| node.attribute(name)) +} +fn inherited<'a>(node: Node<'a, '_>, name: &str) -> Option<&'a str> { + node.ancestors() + .filter(|n| n.is_element()) + .find_map(|n| property(n, name).filter(|v| *v != "inherit")) +} +fn hidden(node: Node) -> Result { + for n in node.ancestors().filter(|n| n.is_element()) { + if property(n, "display") == Some("none") { + return Ok(true); + } + if let Some(v) = property(n, "opacity") { + let opacity = v + .parse::() + .map_err(|_| "Unsupported SVG opacity value.")?; + if !opacity.is_finite() { + return Err("Invalid SVG opacity.".into()); + } + if opacity <= 0.0 { + return Ok(true); + } + } + } + Ok(matches!( + inherited(node, "visibility"), + Some("hidden" | "collapse") + )) +} +fn rectangle_points(mut points: Vec<[f64; 2]>) -> Result { + if points.len() == 5 && points.first() == points.last() { + points.pop(); + } + if points.len() != 4 || points.iter().flatten().any(|v| !v.is_finite()) { + return Err("Only four-corner rectangular SVG paths/polygons are supported.".into()); + } + let minx = points.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min); + let maxx = points + .iter() + .map(|p| p[0]) + .fold(f64::NEG_INFINITY, f64::max); + let miny = points.iter().map(|p| p[1]).fold(f64::INFINITY, f64::min); + let maxy = points + .iter() + .map(|p| p[1]) + .fold(f64::NEG_INFINITY, f64::max); + for j in 0..4 { + let a = points[j]; + let b = points[(j + 1) % 4]; + if !(a[0] == minx || a[0] == maxx) + || !(a[1] == miny || a[1] == maxy) + || a == b + || !((a[0] == b[0]) ^ (a[1] == b[1])) + || points[..j].contains(&a) + { + return Err("SVG path/polygon is not an axis-aligned rectangle.".into()); + } + } + Geometry { + x: minx, + y: miny, + width: maxx - minx, + height: maxy - miny, + } + .validate() +} +fn path_rectangle(data: &str) -> Result { + use svgtypes::PathSegment::*; + let mut points = Vec::new(); + let mut current = [0.0; 2]; + let mut closed = false; + for segment in svgtypes::PathParser::from(data) { + if closed { + return Err("Multiple SVG subpaths are unsupported.".into()); + } + match segment.map_err(|e|format!("Invalid SVG path: {e}"))? { + MoveTo{abs,x,y} if points.is_empty()=>{current=if abs {[x,y]} else {[current[0]+x,current[1]+y]};points.push(current);} + LineTo{abs,x,y} if !points.is_empty()=>{current=if abs {[x,y]} else {[current[0]+x,current[1]+y]};points.push(current);} + HorizontalLineTo{abs,x} if !points.is_empty()=>{current[0]=if abs{x}else{current[0]+x};points.push(current);} + VerticalLineTo{abs,y} if !points.is_empty()=>{current[1]=if abs{y}else{current[1]+y};points.push(current);} + ClosePath{..}=>closed=true, + _=>return Err("Only straight, closed rectangular SVG paths are supported; curves and multiple subpaths are refused.".into()), + } + if points.len() > 5 { + return Err("SVG path contains more than four rectangle corners.".into()); + } + } + if !closed { + return Err("SVG rectangle paths must be closed.".into()); + } + rectangle_points(points) +} +fn walk( + node: Node, + matrix: Matrix, + viewport: [f64; 2], + page: [f64; 2], + out: &mut Vec, + depth: usize, +) -> Result<(), String> { + if depth > 64 { + return Err("SVG nesting exceeds 64 levels.".into()); + } + if !node.is_element() { + return Ok(()); + } + let tag = node.tag_name().name(); + if matches!(tag, "defs" | "metadata" | "title" | "desc" | "namedview") { + return Ok(()); + } + if tag == "style" { + return Err( + "SVG stylesheets are unsupported. Use inline styles or presentation attributes.".into(), + ); + } + if hidden(node)? && !matches!(tag, "svg" | "g" | "a") { + return Ok(()); + } + for name in ["clip-path", "mask", "filter", "transform-origin"] { + if property(node, name).is_some_and(|v| v != "none") { + return Err(format!( + "SVG {name} is unsupported; import plain rectangles without clipping or effects." + )); + } + } + if node.attribute("style").is_some_and(|s| { + s.split(';').any(|part| { + part.split_once(':').is_some_and(|(k, _)| { + matches!( + k.trim(), + "transform" | "x" | "y" | "width" | "height" | "rx" | "ry" + ) + }) + }) + }) { + return Err("SVG CSS geometry/transform is unsupported; use attributes.".into()); + } + let matrix = matrix.nested(node)?; + if matches!(tag, "svg" | "g" | "a") { + if tag == "svg" && depth != 0 { + return Err("Nested SVG viewports are unsupported.".into()); + } + for child in node.children() { + walk(child, matrix, viewport, page, out, depth + 1)?; + } + return Ok(()); + } + let dim = |name: &str, default: Option<&str>, axis: usize| { + length( + node.attribute(name) + .or(default) + .ok_or_else(|| format!("Missing SVG {name}."))?, + Some(viewport[axis]), + ) + }; + let raw = match tag { + "rect" | "image" => { + if tag == "rect" && (dim("rx", Some("0"), 0)? != 0.0 || dim("ry", Some("0"), 1)? != 0.0) + { + return Err("Rounded SVG rectangles are unsupported. Use square corners.".into()); + } + Geometry { + x: dim("x", Some("0"), 0)?, + y: dim("y", Some("0"), 1)?, + width: dim("width", None, 0)?, + height: dim("height", None, 1)?, + } + .validate()? + } + "path" => path_rectangle(node.attribute("d").ok_or("Missing SVG path data.")?)?, + "polygon" => { + let numbers = svgtypes::NumberListParser::from( + node.attribute("points") + .ok_or("Missing SVG polygon points.")?, + ) + .collect::, _>>() + .map_err(|e| format!("Invalid SVG polygon points: {e}"))?; + if numbers.len() % 2 != 0 { + return Err("SVG polygon points need X/Y pairs.".into()); + } + rectangle_points(numbers.as_chunks::<2>().0.to_vec())? + } + _ => { + return Err(format!( + "Unsupported visible SVG element <{tag}>. Export rectangles only (plus an optional full-page background)." + )); + } + }; + let geometry = matrix.bounds(raw)?; + let full_page = geometry.x.abs() < 1e-6 + && geometry.y.abs() < 1e-6 + && (geometry.width - page[0]).abs() < 1e-6 + && (geometry.height - page[1]).abs() < 1e-6; + let background = out.is_empty() && full_page; + if tag == "image" && !background { + return Err("Only a first, full-page SVG image can be ignored as background; other images are unsupported.".into()); + } + let stroke = if inherited(node, "stroke").is_none_or(|v| v == "none") + || inherited(node, "stroke-opacity") == Some("0") + { + 0.0 + } else { + length(inherited(node, "stroke-width").unwrap_or("1"), None)? + }; + if stroke < 0.0 { + return Err("SVG stroke width cannot be negative.".into()); + } + if stroke > 0.0 && inherited(node, "vector-effect").is_some_and(|v| v != "none") { + return Err("SVG non-scaling strokes are unsupported.".into()); + } + if stroke > 0.0 + && matches!(tag, "path" | "polygon") + && inherited(node, "stroke-linejoin").is_some_and(|v| v != "miter") + { + return Err("SVG rectangular paths require miter stroke joins for outline import.".into()); + } + let id = node + .attribute(("http://www.inkscape.org/namespaces/inkscape", "label")) + .or_else(|| node.attribute("id")) + .map(str::to_owned) + .unwrap_or_else(|| format!("{tag} {}", out.len() + 1)); + out.push(DetectedShape { + id, + geometry, + outline: [stroke * matrix.x.abs(), stroke * matrix.y.abs()], + background, + background_only: tag == "image", + }); + if out.len() > 256 { + return Err("Import is limited to 256 rectangles.".into()); + } + Ok(()) +} +pub fn parse_svg(text: &str) -> Result { + if text.len() > 1_048_576 { + return Err("SVG exceeds 1 MiB.".into()); + } + let document = roxmltree::Document::parse(text).map_err(|e| format!("Invalid SVG XML: {e}"))?; + let root = document.root_element(); + if !root.has_tag_name("svg") { + return Err("Choose an SVG file with an root.".into()); + } + if document.descendants().any(|n| { + (n.is_element() && n.has_tag_name("style")) + || n.pi().is_some_and(|pi| pi.target == "xml-stylesheet") + }) { + return Err("SVG stylesheets are unsupported; use inline styles.".into()); + } + let vb = root + .attribute("viewBox") + .map(svgtypes::ViewBox::from_str) + .transpose() + .map_err(|e| format!("Invalid SVG viewBox: {e}"))?; + let viewport = if let Some(v) = vb { + [v.w, v.h] + } else { + [ + length( + root.attribute("width") + .ok_or("SVG needs width/height or a viewBox.")?, + None, + )?, + length( + root.attribute("height") + .ok_or("SVG needs width/height or a viewBox.")?, + None, + )?, + ] + }; + crate::formats::validate_size(viewport)?; + let page = [ + root.attribute("width") + .map(|s| length(s, None)) + .transpose()? + .unwrap_or(viewport[0]), + root.attribute("height") + .map(|s| length(s, None)) + .transpose()? + .unwrap_or(viewport[1]), + ]; + crate::formats::validate_size(page)?; + let mut matrix = Matrix { + x: 1.0, + y: 1.0, + tx: 0.0, + ty: 0.0, + }; + if let Some(v) = vb { + let aspect = root + .attribute("preserveAspectRatio") + .unwrap_or("xMidYMid meet"); + if aspect == "none" { + matrix = Matrix { + x: page[0] / v.w, + y: page[1] / v.h, + tx: -v.x * page[0] / v.w, + ty: -v.y * page[1] / v.h, + }; + } else if matches!(aspect, "xMidYMid" | "xMidYMid meet") { + let k = (page[0] / v.w).min(page[1] / v.h); + matrix = Matrix { + x: k, + y: k, + tx: (page[0] - k * v.w) / 2.0 - v.x * k, + ty: (page[1] - k * v.h) / 2.0 - v.y * k, + }; + } else { + return Err("SVG preserveAspectRatio currently supports xMidYMid meet or none. Other alignments/cropping must be flattened first.".into()); + } + } + let mut shapes = Vec::new(); + walk(root, matrix, viewport, page, &mut shapes, 0)?; + if shapes.is_empty() { + return Err("No visible rectangles detected in SVG.".into()); + } + Ok(ImportDocument { + 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.", + crate::view_pixels(page[0]), + crate::view_pixels(page[1]) + ), + }) +} diff --git a/crates/midra-layout/src/lib.rs b/crates/midra-layout/src/lib.rs index 0a5f4a3..7a7a2c2 100644 --- a/crates/midra-layout/src/lib.rs +++ b/crates/midra-layout/src/lib.rs @@ -1,6 +1,7 @@ -//! Offline layer geometry, reversible edits and a deliberately narrow draw.io adapter. +//! Offline layer geometry, reversible edits and bounded draw.io/SVG imports. use std::collections::HashMap; pub mod formats; +pub mod import; use formats::{Formats, Framing, Source}; /// Presentation only: retain full precision in the document. @@ -544,6 +545,29 @@ impl Layout { next[index] = geometry; self.commit(next) } + /// Apply a one-to-one import to the complete selection, with one undo record. + pub fn apply_import(&mut self, values: &[(usize, Geometry)]) -> Result<(), String> { + let targets = self.selected_indices(); + if values.len() != targets.len() || targets.is_empty() { + return Err(format!( + "Layer count mismatch: {} selected, {} imported. Select exactly one destination for each imported rectangle.", + targets.len(), + values.len() + )); + } + let mut seen = Vec::new(); + let mut next = self.layers; + for (i, g) in values { + if !targets.contains(i) || seen.contains(i) || !self.selectable(*i) { + return Err("Map every selected layer exactly once; duplicate or unselected targets are not allowed.".into()); + } + g.validate()?; + seen.push(*i); + next[*i] = *g; + } + self.finish_drag(); + self.commit(next) + } pub fn nudge(&mut self, dx: f64, dy: f64) -> Result<(), String> { self.finish_drag(); let mut next = self.layers; diff --git a/crates/midra-layout/tests/import.rs b/crates/midra-layout/tests/import.rs new file mode 100644 index 0000000..e17b0b2 --- /dev/null +++ b/crates/midra-layout/tests/import.rs @@ -0,0 +1,183 @@ +use midra_layout::import::{parse_svg, parse_values}; +use midra_layout::{Geometry, Layout}; +fn svg(body: &str) -> String { + format!( + r#"{body}"# + ) +} +fn close(a: f64, b: f64) { + assert!((a - b).abs() < 1e-7, "{a} != {b}"); +} +#[test] +fn svg_detects_rectangles_background_names_transforms_and_outlines() { + let doc=parse_svg(&svg(r#""#)).unwrap(); + assert_eq!(doc.shapes.len(), 3); + assert!(doc.shapes[0].background); + assert!(!doc.shapes[1].background); + assert_eq!(doc.shapes[1].id, "presenter"); + assert_eq!( + doc.shapes[1].geometry, + Geometry { + x: 32.0, + y: 110.0, + width: 200.0, + height: 150.0 + } + ); + assert_eq!(doc.shapes[1].outline, [8.0, 12.0]); + let g = doc.shapes[1] + .paste_geometry(doc.shapes[1].geometry, true, true) + .unwrap(); + assert_eq!( + g, + Geometry { + x: 28.0, + y: 104.0, + width: 208.0, + height: 162.0 + } + ); +} +#[test] +fn svg_units_viewbox_letterboxing_and_preserve_aspect_none_are_applied() { + let d=parse_svg(r#""#).unwrap(); + let g = d.shapes[0].geometry; + close(g.x, 0.0); + close(g.y, 0.0); + close(g.width, 192.0); + close(g.height, 96.0); + let d=parse_svg(r#""#).unwrap(); + assert_eq!( + d.shapes[0].geometry, + Geometry { + x: 0.0, + y: 50.0, + width: 200.0, + height: 100.0 + } + ); + let d=parse_svg(r#""#).unwrap(); + assert_eq!( + d.shapes[0].geometry, + Geometry { + x: 0.0, + y: 0.0, + width: 200.0, + height: 200.0 + } + ); + assert!(d.shapes[0].background); +} +#[test] +fn rectangular_paths_polygons_hidden_nodes_and_image_background_are_handled() { + let doc=parse_svg(&svg(r#""#)).unwrap(); + assert_eq!(doc.shapes.len(), 3); + assert!(doc.shapes[0].background_only); + assert!( + doc.shapes[0] + .paste_geometry(doc.shapes[0].geometry, true, false) + .is_err() + ); + assert_eq!( + doc.shapes[1].geometry, + Geometry { + x: 12.0, + y: 30.0, + width: 100.0, + height: 50.0 + } + ); + assert_eq!( + doc.shapes[2].geometry, + Geometry { + x: 200.0, + y: 30.0, + width: 100.0, + height: 50.0 + } + ); + let d = parse_svg(&svg( + r#""#, + )) + .unwrap(); + assert_eq!(d.shapes.len(), 1); +} +#[test] +fn unsupported_or_ambiguous_svg_is_refused_without_partial_shapes() { + for body in [ + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r#""#, + r##""##, + r#""#, + r#""#, + ] { + assert!(parse_svg(&svg(body)).is_err(), "accepted {body}"); + } + assert!( + parse_svg(r#""#) + .is_err() + ); + assert!(parse_svg("not xml").is_err()); + assert!(parse_values(&"x".repeat(1_048_577)).is_err()); +} +#[test] +fn batch_import_is_one_transaction_and_refuses_count_duplicates_and_invalid_geometry() { + let mut l = Layout::default(); + l.set_selection([true; 2]); + let before = *l.layers(); + let formats = *l.formats(); + let a = Geometry { + x: 12.0, + y: 271.0, + width: 945.0, + height: 531.58, + }; + let b = Geometry { + x: 1000.0, + y: 60.0, + width: 300.0, + height: 250.0, + }; + assert!( + l.apply_import(&[(0, a)]) + .unwrap_err() + .contains("count mismatch") + ); + assert!(l.apply_import(&[(0, a), (0, b)]).is_err()); + assert!( + l.apply_import(&[(0, a), (1, Geometry { width: -1.0, ..b })]) + .is_err() + ); + assert_eq!(*l.layers(), before); + assert_eq!(*l.formats(), formats); + l.apply_import(&[(1, a), (0, b)]).unwrap(); + assert_eq!(*l.layers(), [b, a]); + l.undo(); + assert_eq!(*l.layers(), before); + assert_eq!(*l.formats(), formats); + l.redo(); + assert_eq!(*l.layers(), [b, a]); + l.set_locked(1, true); + assert!(l.apply_import(&[(0, a), (1, b)]).is_err()); +} +#[test] +fn drawio_auto_detection_and_svg_text_preserve_fractional_bounds() { + let d = parse_values(include_str!("fixtures/drawio-rectangle.txt")).unwrap(); + assert!(!d.svg); + assert_eq!(d.shapes[0].geometry.height, 531.58); + let d = parse_values(&svg( + r#""#, + )) + .unwrap(); + assert!(d.svg); + assert_eq!(d.shapes[0].geometry.x, 12.25); +} diff --git a/docs/midra-layout.md b/docs/midra-layout.md index e268555..7a231ae 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -1,7 +1,7 @@ # Midra Layout A native Rust/egui workspace for positioning two rectangular layers offline. -Select layers, paste draw.io geometry, move them visually or enter exact corner +Select layers, paste draw.io or import SVG geometry, move them visually or enter exact corner positions and dimensions. Configure source/input formats and content framing; visible-box coordinates and provisional crop calculations update together. No device connection or REST calls are made. @@ -10,19 +10,49 @@ No device connection or REST calls are made. cargo run --locked -p midra-layout ``` -## Paste from draw.io +## Paste layer values and import SVG -1. Select the target layer on the canvas or in the right-hand list. -2. Copy an ungrouped rectangle in draw.io, then press **Ctrl/Cmd-V** with the - viewport focused. Alternatively, click **Paste draw.io…**, paste into the text - area and click **Read geometry**. -3. Review the target layer, before/after position and size. If multiple rectangles - were copied, choose one explicitly; the importer does not guess a mapping to - the two layers. +1. Select the destination layers on the canvas or in the right-hand list + (Shift-click to select both). +2. Copy rectangles in draw.io, then press **Ctrl/Cmd-V** with the viewport + focused. Alternatively, click **Paste layer(s) values**, paste into the text + area and click **Read geometry**. **Import SVG…** opens an SVG file in the + same review window; raw SVG XML can also be pasted. +3. Review each detected rectangle and choose its destination layer. Initial + mapping follows document order and the selected layer list. Every selected + destination must receive exactly one rectangle: count mismatches and duplicate + mappings block Apply and explain what needs changing. Nothing changes yet. 4. Leave **Include size / format** checked to import width and height along with position, or uncheck it for position only. Choose **Include outline in bounds** - if the layer should cover the rectangle's outline too, then click - **Apply to selected target**. The before/after preview updates with your choice. + if the layer should cover the rectangle's outline too. +5. Click **Apply mapped values** to update the entire selection in one undo step. + Cancel leaves all layers unchanged. Invalid geometry or incompatible framing + blocks the whole batch, without partial changes. + +The current workspace has two layers; the import review handles all selected +layers rather than choosing one rectangle from a larger clipboard selection. + +### SVG bounds + +SVG import accepts square-corner rectangles and simple closed rectangular +paths/polygons, including translated/scaled groups and inline styles. It applies +page dimensions and `viewBox` transforms, using CSS units at 96 px/in. Coordinates +are relative to the SVG page; exporting only a selection may lose its original +document position. The SVG is used for bounds, not rendered as a reference image. + +A first full-page rectangle or image is marked as a possible background. Check +**Ignore full-page background** to exclude it from the count and mapping. This +is explicit: a full-page rectangle can also be a real layer. Image backgrounds +must be excluded; their contents and external links are never loaded. + +Other visible artwork, rotation/skew, rounded rectangles, clipping, masks, +filters, stylesheets, and unsupported SVG features are refused with an error. +Hidden objects and definitions are ignored. Export simple rectangles with inline +styles for predictable results. Files are limited to 1 MiB, 256 rectangles, and +64 levels of nesting. SVG imports retain the same outline and position-only +choices as draw.io imports. + +### draw.io clipboard The first adapter accepts raw or once-percent-encoded `mxGraphModel` XML, like [the supplied clipboard fixture](../crates/midra-layout/tests/fixtures/drawio-rectangle.txt). @@ -113,11 +143,11 @@ Use **Align left**, **Align right**, **Align top**, **Align bottom**, **Center X the relevant position axis, never size, and is one undo step. The inspector lists each layer's resulting center coordinates. Single-layer numeric fields are replaced by alignment controls during multi-selection; no mixed values are shown -as if they belonged to one layer. Select exactly one layer to paste or resize. +as if they belonged to one layer. Select exactly one layer to resize; paste/import accepts the full selection. Text inputs receive normal text paste and arrow navigation while focused; they never interpret these actions as geometry import or layer movement. Paste preview -identifies its target explicitly and changes only that layer. +identifies every destination explicitly and applies the mapped selection together. ## Current limits