Add SVG and draw.io layer exchange with optional artwork

This commit is contained in:
Dandaedre 2026-11-14 14:41:24 +01:00
parent e440d91ed5
commit 6a51d2266b
17 changed files with 960 additions and 136 deletions

1
Cargo.lock generated
View File

@ -2549,6 +2549,7 @@ dependencies = [
"base64 0.22.1",
"directories",
"eframe",
"flate2",
"image",
"reqwest",
"rfd",

View File

@ -15,6 +15,7 @@ svgtypes = "0.15"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
base64 = "0.22"
flate2 = "1"
tempfile = "3"
directories = "6"
reqwest = { version = "0.12.28", default-features = false, features = ["blocking"] }

View File

@ -0,0 +1,64 @@
//! Manual native-editor round trip; all paths are explicit, no device access.
use midra_layout::{
Layout,
exchange::{self, Format, Options},
import::parse_values,
project::{Project, write_file},
};
fn main() -> Result<(), String> {
let args: Vec<_> = std::env::args().skip(1).collect();
match args.as_slice() {
[command, directory] if command == "generate" => {
let directory = std::path::Path::new(directory);
std::fs::create_dir_all(directory).map_err(|e| e.to_string())?;
let project = Project::from_layout(&Layout::default());
let ids = project.layers.iter().map(|l| l.id).collect::<Vec<_>>();
for format in [Format::Svg, Format::Drawio] {
for (name, options) in [
("plain", Options::default()),
(
"illustrated",
Options {
background: true,
placeholders: true,
},
),
] {
let contents = exchange::export(&project, &ids, format, options)?;
write_file(
&directory.join(format!("{name}.{}", format.extension())),
contents.as_bytes(),
false,
)?;
}
}
}
[command, paths @ ..] if command == "verify" && !paths.is_empty() => {
let project = Project::from_layout(&Layout::default());
for path in paths {
let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
let imported = parse_values(&text)?;
let shapes: Vec<_> = imported
.shapes
.iter()
.filter(|s| !s.background_only)
.collect();
if shapes.len() != project.layers.len()
|| shapes
.iter()
.zip(&project.layers)
.any(|(s, l)| s.geometry != l.bounds)
{
return Err(format!("Geometry mismatch: {path}"));
}
println!("Verified {} layer boxes: {path}", shapes.len());
}
}
_ => {
return Err(
"Usage: check_geometry_exchange generate DIRECTORY | verify FILE...".into(),
);
}
}
Ok(())
}

View File

@ -0,0 +1,244 @@
//! SVG/draw.io geometry interchange with self-contained optional artwork.
use crate::{
Geometry, export_pixels,
project::{Layer, Project},
};
use base64::{Engine, engine::general_purpose::STANDARD};
use image::{Rgba, RgbaImage};
use std::io::Cursor;
pub const MAX_EXCHANGE_BYTES: usize = 16 * 1024 * 1024;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Format {
#[default]
Svg,
Drawio,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Options {
pub background: bool,
pub placeholders: bool,
}
impl Format {
pub fn extension(self) -> &'static str {
match self {
Self::Svg => "svg",
Self::Drawio => "drawio",
}
}
pub fn label(self) -> &'static str {
match self {
Self::Svg => "SVG",
Self::Drawio => "draw.io",
}
}
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;")
.replace('<', "&lt;")
.replace('>', "&gt;")
.replace('"', "&quot;")
.replace('\'', "&apos;")
}
fn png(image: RgbaImage) -> Result<String, String> {
let mut bytes = Cursor::new(Vec::new());
image
.write_to(&mut bytes, image::ImageFormat::Png)
.map_err(|e| e.to_string())?;
Ok(STANDARD.encode(bytes.into_inner()))
}
fn thumbnail_size(w: f64, h: f64, max: f64) -> [u32; 2] {
let scale = (max / w.max(h)).min(1.0);
[
(w * scale).round().max(1.0) as u32,
(h * scale).round().max(1.0) as u32,
]
}
fn placeholder(project: &Project, layer: &Layer) -> Result<String, String> {
let source = project
.inputs
.iter()
.find(|i| i.id == layer.source_id)
.ok_or("Missing source")?;
let native = [
source.native_resolution.width as f64,
source.native_resolution.height as f64,
];
let input = source.input_crop.remaining(native)?;
let remaining = layer.advanced_crop.remaining(input)?;
let [w, h] = thumbnail_size(layer.bounds.width, layer.bounds.height, 512.0);
let image = RgbaImage::from_fn(w, h, |x, y| {
let sx = source.input_crop.left
+ layer.advanced_crop.left
+ (x as f64 + 0.5) / w as f64 * remaining[0];
let sy = source.input_crop.top
+ layer.advanced_crop.top
+ (y as f64 + 0.5) / h as f64 * remaining[1];
let gx = sx / native[0] * 10.0;
let gy = sy / native[1] * 6.0;
if gx.fract() < 0.025 || gy.fract() < 0.025 {
Rgba([210, 221, 230, 255])
} else if (gx as u32 + gy as u32).is_multiple_of(2) {
Rgba([35, 69, 87, 255])
} else {
Rgba([23, 47, 63, 255])
}
});
png(image)
}
fn background(project: &Project) -> Result<String, String> {
let ow = project.output_resolution.width as f64;
let oh = project.output_resolution.height as f64;
let [w, h] = thumbnail_size(ow, oh, 1920.0);
let mut canvas = RgbaImage::from_pixel(w, h, Rgba([18, 37, 49, 255]));
if let Some(reference) = project.reference.as_ref().filter(|r| r.visible) {
let bytes = reference.bytes()?;
let mut reader = image::ImageReader::new(Cursor::new(bytes))
.with_guessed_format()
.map_err(|e| e.to_string())?;
let mut limits = image::Limits::default();
limits.max_image_width = Some(8192);
limits.max_image_height = Some(8192);
limits.max_alloc = Some(256 * 1024 * 1024);
reader.limits(limits);
let image = reader
.decode()
.map_err(|e| format!("Cannot decode reference: {e}"))?
.to_rgba8();
let iw = image.width() as f64;
let ih = image.height() as f64;
let (rw, rh, x, y) = if reference.native_size {
(iw, ih, 0.0, 0.0)
} else if reference.preserve_ratio {
let k = (ow / iw).min(oh / ih);
(iw * k, ih * k, (ow - iw * k) / 2.0, (oh - ih * k) / 2.0)
} else {
(ow, oh, 0.0, 0.0)
};
for (px, py, out) in canvas.enumerate_pixels_mut() {
let sx = ((px as f64 + 0.5) * ow / w as f64 - x - reference.offset[0]) / rw * iw;
let sy = ((py as f64 + 0.5) * oh / h as f64 - y - reference.offset[1]) / rh * ih;
if sx >= 0.0 && sy >= 0.0 && sx < iw && sy < ih {
let source = image.get_pixel(sx as u32, sy as u32);
let alpha = source[3] as f32 / 255.0 * reference.opacity;
for c in 0..3 {
out[c] =
(source[c] as f32 * alpha + out[c] as f32 * (1.0 - alpha)).round() as u8;
}
}
}
}
png(canvas)
}
/// Export explicit stable IDs, in document order; coordinates stay on the output canvas.
pub fn export(
project: &Project,
ids: &[usize],
format: Format,
options: Options,
) -> Result<String, String> {
project.layout()?;
if ids.is_empty()
|| ids
.iter()
.enumerate()
.any(|(i, id)| ids[..i].contains(id) || !project.layers.iter().any(|l| l.id == *id))
{
return Err("Choose distinct existing layer IDs to export.".into());
}
let w = project.output_resolution.width;
let h = project.output_resolution.height;
let mut out = match format {
Format::Svg => format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" data-midra-layout-geometry=\"2\" width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\">\n<title>Midra Layout geometry</title>\n"
),
Format::Drawio => format!(
"<mxfile host=\"Midra Layout\" compressed=\"false\"><diagram id=\"midra-layout\" name=\"Layout\"><mxGraphModel page=\"1\" pageScale=\"1\" pageWidth=\"{w}\" pageHeight=\"{h}\" grid=\"0\" adaptiveColors=\"none\" data-midra-layout-geometry=\"1\"><root><mxCell id=\"0\"/><mxCell id=\"1\" parent=\"0\"/>\n"
),
};
if options.background {
let image = background(project)?;
let geometry = Geometry {
x: 0.0,
y: 0.0,
width: w as f64,
height: h as f64,
};
element(
&mut out,
format,
"midra-background",
"Background",
geometry,
Some(&image),
true,
);
}
for layer in project.layers.iter().filter(|l| ids.contains(&l.id)) {
let g = layer.bounds;
if g.width.round() < 1.0 || g.height.round() < 1.0 {
return Err("A layer rounds to zero pixels; enlarge it before export.".into());
}
let image = options
.placeholders
.then(|| placeholder(project, layer))
.transpose()?;
element(
&mut out,
format,
&format!("layer-{}", layer.id),
&layer.name,
g,
image.as_deref(),
false,
);
}
out.push_str(match format {
Format::Svg => "</svg>\n",
Format::Drawio => "</root></mxGraphModel></diagram></mxfile>\n",
});
if out.len() > MAX_EXCHANGE_BYTES {
return Err(
"Export exceeds 16 MiB; disable placeholder pictures or the background.".into(),
);
}
Ok(out)
}
fn element(
out: &mut String,
format: Format,
id: &str,
name: &str,
g: Geometry,
image: Option<&str>,
background: bool,
) {
let [x, y, w, h] = [g.x, g.y, g.width, g.height].map(export_pixels);
let role = if background { "background" } else { "layer" };
let name = if background {
String::new()
} else {
escape(name)
};
match format {
Format::Svg => {
let attributes = format!(
"id=\"{id}\" data-midra-role=\"{role}\" x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\""
);
if let Some(image) = image {
out.push_str(&format!("<image {attributes} preserveAspectRatio=\"none\" xlink:href=\"data:image/png;base64,{image}\"><title>{name}</title></image>\n"));
} else {
out.push_str(&format!(
"<rect {attributes} fill=\"#173b50\"><title>{name}</title></rect>\n"
));
}
}
Format::Drawio => {
// mxGraph stores image data without the ';base64' delimiter inside styles.
let image = image
.map(|data| format!("shape=image;imageAspect=0;image=data:image/png,{data};"))
.unwrap_or_default();
out.push_str(&format!("<mxCell id=\"{id}\" value=\"{name}\" data-midra-role=\"{role}\" vertex=\"1\" parent=\"1\" style=\"rounded=0;whiteSpace=wrap;html=0;strokeColor=none;fillColor=#173b50;fontColor=#ffffff;{image}\"><mxGeometry x=\"{x}\" y=\"{y}\" width=\"{w}\" height=\"{h}\" as=\"geometry\"/></mxCell>\n"));
}
}
}

View File

@ -18,7 +18,7 @@ mod recovery_ui;
#[path = "viewport_guides.rs"]
mod viewport_guides;
use format_ui::{FormatDraft, OutputDraft, PropertyTab};
use midra_layout::import::{DetectedShape, ImportDocument, parse_svg, parse_values};
use midra_layout::import::{DetectedShape, ImportDocument, parse_values};
use midra_layout::{
AlignTarget, Alignment, Corner, Geometry, Layout, PositionPoint, PositionReference,
ResizeHandle, ResizeMode,
@ -99,7 +99,6 @@ struct Paste {
shapes: Vec<DetectedShape>,
mapping: Vec<Option<usize>>,
ignored: Vec<bool>,
svg: bool,
note: String,
include_size: bool,
include_position: bool,
@ -111,9 +110,12 @@ struct Paste {
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.ignored = self
.shapes
.iter()
.map(|shape| shape.background_only)
.collect();
self.reset_mapping();
self.error.clear();
}
@ -567,7 +569,6 @@ impl Editor {
shapes: Vec::new(),
mapping: Vec::new(),
ignored: Vec::new(),
svg: false,
note: String::new(),
include_size: true,
include_position: true,
@ -583,7 +584,7 @@ impl Editor {
}
fn import_svg_file(&mut self) {
if let Some(path) = rfd::FileDialog::new()
.add_filter("SVG", &["svg"])
.add_filter("Layer geometry (SVG / draw.io)", &["svg", "drawio", "xml"])
.pick_file()
{
self.open_paste(String::new());
@ -597,11 +598,11 @@ impl Editor {
let result = (|| {
let mut text = String::new();
std::fs::File::open(path)
.map_err(|e| format!("Cannot open SVG: {e}"))?
.take(1_048_577)
.map_err(|e| format!("Cannot open geometry file: {e}"))?
.take(midra_layout::exchange::MAX_EXCHANGE_BYTES as u64 + 1)
.read_to_string(&mut text)
.map_err(|e| format!("Cannot read SVG: {e}"))?;
let doc = parse_svg(&text)?;
.map_err(|e| format!("Cannot read geometry file: {e}"))?;
let doc = midra_layout::import::parse_values(&text)?;
p.text = text;
Ok(doc)
})();
@ -876,7 +877,7 @@ impl Editor {
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 ui.button("Import SVG / draw.io…").clicked() && let Some(path)=rfd::FileDialog::new().add_filter("Layer geometry", &["svg", "drawio", "xml"]).pick_file() {Self::read_svg(&path,&mut p);}
});
if !p.error.is_empty() {ui.colored_label(palette.amber,&p.error);}
if p.shapes.is_empty() {return;}
@ -904,7 +905,9 @@ impl Editor {
ui.small(bounds(shape.geometry));
if let Some(zoom)=shape.zoom {ui.small(format!("Crop zoom: {:.1}%{}",zoom*100.0,if p.include_zoom { " (will apply)" } else { " (not applied)" }));}
else if p.include_zoom && p.zoom_available() {ui.small("No crop zoom in this rectangle; destination zoom is retained.");}
if p.svg && shape.background {
if shape.background_only {
ui.small("Background artwork · excluded from layer mapping");
} else if shape.background {
reset_mapping|=ui.checkbox(&mut p.ignored[row],"Ignore full-page background").changed();
}
if !p.ignored[row] {
@ -5906,6 +5909,32 @@ mod tests {
assert!(app.paste.as_ref().unwrap().closing);
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn exchange_background_is_automatically_excluded_from_mapping() {
use midra_layout::exchange::{self, Format, Options};
for format in [Format::Svg, Format::Drawio] {
let mut app = Editor::default();
app.layout.set_selection([true; 2]);
let project = midra_layout::project::Project::from_layout(&app.layout);
let ids = project.layers.iter().map(|l| l.id).collect::<Vec<_>>();
let text = exchange::export(
&project,
&ids,
format,
Options {
background: true,
placeholders: true,
},
)
.unwrap();
app.open_paste(text);
let paste = app.paste.as_ref().unwrap();
assert_eq!(paste.ignored, vec![true, false, false]);
assert_eq!(paste.mapping, vec![None, Some(0), Some(1)]);
assert_eq!(paste.values(&app.layout).unwrap().len(), 2);
}
}
#[test]
fn import_review_excludes_background_and_applies_reversed_mapping_atomically() {
let mut app = Editor::default();

View File

@ -45,8 +45,8 @@ pub struct ImportDocument {
pub note: String,
}
pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
if text.len() > 1_048_576 {
return Err("Import text exceeds 1 MiB.".into());
if text.len() > crate::exchange::MAX_EXCHANGE_BYTES {
return Err("Import text exceeds 16 MiB.".into());
}
if text.contains(" — visible box (device container unverified)") {
return parse_midra_values(text);
@ -63,8 +63,8 @@ pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
id: s.id,
geometry: s.geometry,
outline: [s.stroke_width; 2],
background: false,
background_only: false,
background: s.background,
background_only: s.background,
zoom: None,
})
.collect(),
@ -419,15 +419,26 @@ fn walk(
&& geometry.y.abs() < 1e-6
&& (geometry.width - page[0]).abs() < 1e-6
&& (geometry.height - page[1]).abs() < 1e-6;
let exported_layer = tag == "rect"
&& node
.document()
.root_element()
.attribute("data-midra-layout-geometry")
== Some("1");
let background = out.is_empty() && full_page && !exported_layer;
if tag == "image" && !background {
return Err("Only a first, full-page SVG image can be ignored as background; other images are unsupported.".into());
let version = node
.document()
.root_element()
.attribute("data-midra-layout-geometry");
let exported_layer = match version {
Some("1") => tag == "rect",
Some("2") => node.attribute("data-midra-role") == Some("layer"),
_ => false,
};
let marked_background =
version == Some("2") && node.attribute("data-midra-role") == Some("background");
if marked_background && !full_page {
return Err("Exported background must cover the SVG page.".into());
}
let background = marked_background || (out.is_empty() && full_page && !exported_layer);
if tag == "image" && !background && !exported_layer {
return Err(
"Only a full-page background or an exported layer placeholder image is supported."
.into(),
);
}
let stroke = if inherited(node, "stroke").is_none_or(|v| v == "none")
|| inherited(node, "stroke-opacity") == Some("0")
@ -458,20 +469,25 @@ fn walk(
geometry,
outline: [stroke * matrix.x.abs(), stroke * matrix.y.abs()],
background,
background_only: tag == "image",
background_only: background && (tag == "image" || marked_background),
zoom: None,
});
if out.len() > 256 {
if out.iter().filter(|s| !s.background_only).count() > 256 || out.len() > 257 {
return Err("Import is limited to 256 rectangles.".into());
}
Ok(())
}
pub fn parse_svg(text: &str) -> Result<ImportDocument, String> {
if text.len() > 1_048_576 {
return Err("SVG exceeds 1 MiB.".into());
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 root = document.root_element();
if let Some(version) = root.attribute("data-midra-layout-geometry")
&& !matches!(version, "1" | "2")
{
return Err("Unsupported Midra SVG exchange version.".into());
}
if !root.has_tag_name("svg") {
return Err("Choose an SVG file with an <svg> root.".into());
}

View File

@ -2,6 +2,7 @@
pub mod device;
pub mod device_send;
use std::collections::HashMap;
pub mod exchange;
pub mod formats;
pub mod import;
pub mod project;
@ -1751,6 +1752,7 @@ pub struct DrawioShape {
pub geometry: Geometry,
/// Effective visible outline thickness, in diagram pixels (default 1).
pub stroke_width: f64,
pub background: bool,
}
impl DrawioShape {
/// Outline expansion applies only when importing size; position-only keeps
@ -1775,11 +1777,12 @@ impl DrawioShape {
}
}
/// Read raw or once-percent-encoded mxGraphModel XML. Values map 1:1 to pixels.
/// Read raw/percent-encoded mxGraphModel or a single-page mxfile (compressed or plain).
/// Values map 1:1 to pixels.
/// Nested, relative, rotated and nonrectangular geometry is intentionally refused.
pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
if input.len() > 1_048_576 {
return Err("Clipboard text exceeds 1 MiB.".into());
if input.len() > exchange::MAX_EXCHANGE_BYTES {
return Err("Diagram exceeds 16 MiB.".into());
}
let input = input.trim();
let decoded;
@ -1789,10 +1792,13 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
decoded = decode_percent(input)?;
decoded.trim()
};
let doc = roxmltree::Document::parse(xml).map_err(|e| format!("Invalid draw.io XML: {e}"))?;
let xml = drawio_model(xml)?;
let doc = roxmltree::Document::parse(&xml).map_err(|e| format!("Invalid draw.io XML: {e}"))?;
let model = doc.root_element();
if !model.has_tag_name("mxGraphModel") {
return Err("Paste draw.io mxGraphModel XML, not a compressed file or an image.".into());
if let Some(version) = model.attribute("data-midra-layout-geometry")
&& version != "1"
{
return Err("Unsupported Midra draw.io exchange version.".into());
}
let root = model
.children()
@ -1845,7 +1851,7 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
.split_once('=')
.ok_or("Named/inherited draw.io styles are unsupported.")?;
styles.insert(key, value);
if (key == "shape" && value != "rectangle")
if (key == "shape" && !matches!(value, "rectangle" | "image"))
|| (matches!(key, "rotation" | "flipH" | "flipV") && value != "0")
{
return Err("Only unrotated rectangles are supported; remove shape transforms before copying.".into());
@ -1896,13 +1902,63 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
id: id.to_owned(),
geometry,
stroke_width,
background: cell.attribute("data-midra-role") == Some("background")
|| id == "midra-background",
});
if result.iter().filter(|s| !s.background).count() > 256
|| result.iter().filter(|s| s.background).count() > 1
{
return Err("Import is limited to 256 layers plus one background.".into());
}
}
if result.is_empty() {
return Err("No rectangles found in the draw.io clipboard.".into());
}
Ok(result)
}
fn drawio_model(xml: &str) -> Result<String, String> {
use base64::{Engine, engine::general_purpose::STANDARD};
use std::io::Read;
let doc = roxmltree::Document::parse(xml).map_err(|e| format!("Invalid draw.io XML: {e}"))?;
let root = doc.root_element();
if root.has_tag_name("mxGraphModel") {
return Ok(xml.into());
}
if !root.has_tag_name("mxfile") {
return Err("Choose draw.io XML or a .drawio file.".into());
}
let pages: Vec<_> = root
.children()
.filter(|n| n.has_tag_name("diagram"))
.collect();
if pages.len() != 1 {
return Err("Import one draw.io page at a time; export the required page as XML.".into());
}
if let Some(model) = pages[0].children().find(|n| n.has_tag_name("mxGraphModel")) {
return Ok(xml[model.range()].into());
}
let data = STANDARD
.decode(pages[0].text().unwrap_or("").trim())
.map_err(|e| format!("Invalid compressed diagram: {e}"))?;
let mut encoded = String::new();
flate2::read::DeflateDecoder::new(data.as_slice())
.take(exchange::MAX_EXCHANGE_BYTES as u64 * 3 + 1)
.read_to_string(&mut encoded)
.map_err(|e| format!("Cannot decompress diagram: {e}"))?;
if encoded.len() > exchange::MAX_EXCHANGE_BYTES * 3 {
return Err("Decompressed diagram exceeds limit.".into());
}
let model = decode_percent(&encoded)?;
if model.len() > exchange::MAX_EXCHANGE_BYTES {
return Err("Decompressed diagram exceeds 16 MiB.".into());
}
if !roxmltree::Document::parse(&model)
.is_ok_and(|d| d.root_element().has_tag_name("mxGraphModel"))
{
return Err("Compressed diagram must contain mxGraphModel XML.".into());
}
Ok(model)
}
fn decode_percent(input: &str) -> Result<String, String> {
let mut out = Vec::with_capacity(input.len());
let mut bytes = input.bytes();

View File

@ -50,7 +50,7 @@ impl Editor {
ui.separator();
ui.weak("Layer values");
self.transfer_layer_picker(ui, "Choose destination layers…");
if ui.button("SVG file…").clicked() {
if ui.button("SVG / draw.io file…").clicked() {
ui.close_menu();
self.import_svg_file();
}

View File

@ -13,6 +13,7 @@ pub(super) struct FileUi {
opening: Option<(PathBuf, Project)>,
writing: Option<(PathBuf, String)>,
pub(super) message: Option<String>,
exchange_options: midra_layout::exchange::Options,
}
impl Editor {
pub(super) fn project(&self) -> Project {
@ -231,87 +232,94 @@ impl Editor {
ui.close_menu();
}
ui.separator();
ui.menu_button("Export SVG", |ui| {
self.transfer_layer_picker(ui, "Choose layers to export…");
ui.menu_button("Specific layer…", |ui| {
egui::ScrollArea::vertical()
.max_height(320.0)
.show(ui, |ui| {
for i in 0..self.layout.layers().len() {
let title = format!(
"{}{}",
self.layout.layer_label(i),
if self.layout.visible(i) {
""
} else {
" (hidden)"
}
);
if ui.button(title).clicked() {
ui.close_menu();
match self.project().to_svg_ids(&[self.layout.layer_info(i).id]) {
Ok(svg) => {
if let Some(path) = rfd::FileDialog::new()
.add_filter("SVG geometry", &["svg"])
.set_file_name("layer.svg")
.save_file()
{
self.queue_write(path, svg);
}
}
Err(e) => self.files.message = Some(e),
}
}
}
});
for format in [
midra_layout::exchange::Format::Svg,
midra_layout::exchange::Format::Drawio,
] {
ui.menu_button(format!("Export {}", format.label()), |ui| {
self.exchange_menu(ui, format)
});
if ui
.add_enabled(
!self.layout.selected_indices().is_empty(),
egui::Button::new("Selected layers…"),
)
.clicked()
{
ui.close_menu();
let ids: Vec<_> = self
.layout
.selected_indices()
.iter()
.map(|i| self.layout.layer_info(*i).id)
.collect();
match self.project().to_svg_ids(&ids) {
Ok(svg) => {
if let Some(path) = rfd::FileDialog::new()
.add_filter("SVG geometry", &["svg"])
.set_file_name("selection.svg")
.save_file()
{
self.queue_write(path, svg);
}
}
fn exchange_menu(&mut self, ui: &mut egui::Ui, format: midra_layout::exchange::Format) {
ui.checkbox(&mut self.files.exchange_options.background, "Include background layer")
.on_hover_text("Embed the visible reference image on a screen-sized background, or a plain backdrop when none is visible.");
ui.checkbox(&mut self.files.exchange_options.placeholders, "Include placeholder pictures")
.on_hover_text("Embed source-pattern pictures showing current cropping. These are placeholders, not live source captures.");
ui.separator();
let current = self.layout.selected().map(|i| self.layout.layer_info(i).id);
if ui
.add_enabled(current.is_some(), egui::Button::new("Current layer…"))
.on_disabled_hover_text("Select exactly one layer.")
.clicked()
{
ui.close_menu();
self.export_exchange(format, &[current.unwrap()], "layer");
}
self.transfer_layer_picker(ui, "Choose layers to export…");
ui.menu_button("Specific layer…", |ui| {
egui::ScrollArea::vertical()
.max_height(320.0)
.show(ui, |ui| {
for i in 0..self.layout.layers().len() {
if ui.button(self.layout.layer_label(i)).clicked() {
let id = self.layout.layer_info(i).id;
ui.close_menu();
self.export_exchange(format, &[id], "layer");
}
}
Err(e) => self.files.message = Some(e),
}
}
for (title, visible_only) in [("All layers…", false), ("Visible layers only…", true)]
{
if ui.button(title).clicked() {
ui.close_menu();
match self.project().to_svg(visible_only) {
Ok(svg) => {
if let Some(path) = rfd::FileDialog::new()
.add_filter("SVG geometry", &["svg"])
.set_file_name("layout.svg")
.save_file()
{
self.queue_write(path, svg);
}
}
Err(e) => self.files.message = Some(e),
}
}
}
ui.small("Pixel-rounded layer boxes; use JSON to preserve crops and sources.");
});
});
let selected: Vec<_> = self
.layout
.selected_indices()
.iter()
.map(|&i| self.layout.layer_info(i).id)
.collect();
if ui
.add_enabled(!selected.is_empty(), egui::Button::new("Selected layers…"))
.clicked()
{
ui.close_menu();
self.export_exchange(format, &selected, "selection");
}
for (label, visible) in [("All layers…", false), ("Visible layers only…", true)] {
if ui.button(label).clicked() {
let ids: Vec<_> = (0..self.layout.layers().len())
.filter(|&i| !visible || self.layout.visible(i))
.map(|i| self.layout.layer_info(i).id)
.collect();
ui.close_menu();
self.export_exchange(format, &ids, "layout");
}
}
ui.small(
"Round-trip layer boxes in screen pixels. JSON preserves full source/crop settings.",
);
}
fn export_exchange(
&mut self,
format: midra_layout::exchange::Format,
ids: &[usize],
name: &str,
) {
match midra_layout::exchange::export(
&self.project(),
ids,
format,
self.files.exchange_options,
) {
Ok(contents) => {
if let Some(path) = rfd::FileDialog::new()
.add_filter(format.label(), &[format.extension()])
.set_file_name(format!("{name}.{}", format.extension()))
.save_file()
{
self.queue_write(path, contents);
}
}
Err(error) => self.files.message = Some(error),
}
}
pub(super) fn project_windows(&mut self, ctx: &egui::Context) {
if let Some((path, project)) = self.files.opening.take() {
@ -378,6 +386,36 @@ impl Editor {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn both_exchange_menus_offer_current_layer_and_shared_artwork_options() {
let ctx = egui::Context::default();
let mut app = Editor::default();
// Render the real submenu directly so file-dialog actions remain untouched.
for format in [
midra_layout::exchange::Format::Svg,
midra_layout::exchange::Format::Drawio,
] {
let output = ctx.run(egui::RawInput::default(), |ctx| {
egui::CentralPanel::default().show(ctx, |ui| app.exchange_menu(ui, format));
});
for label in [
"Current layer…",
"Include background layer",
"Include placeholder pictures",
"Selected layers…",
"All layers…",
"Visible layers only…",
] {
assert!(
output.shapes.iter().any(
|s| matches!(&s.shape, egui::Shape::Text(t) if t.galley.text() == label)
),
"{label}"
);
}
}
}
#[test]
fn new_after_save_requires_success_and_does_not_count_autosave() {
let dir = tempfile::tempdir().unwrap();

View File

@ -0,0 +1,222 @@
use base64::{Engine, engine::general_purpose::STANDARD};
use midra_layout::{
Geometry, Layout,
exchange::{self, Format, Options},
import::parse_values,
project::Project,
};
use std::io::Write;
fn fixture() -> Project {
let mut layout = Layout::default();
layout
.apply(
0,
Geometry {
x: -12.5,
y: 271.4,
width: 945.2,
height: 531.58,
},
)
.unwrap();
layout
.rename_layer(0, "Camera & <left> \"wide\"", "")
.unwrap();
Project::from_layout(&layout)
}
#[test]
fn every_format_and_artwork_option_roundtrips_geometry_and_order() {
let project = fixture();
let ids: Vec<_> = project.layers.iter().map(|l| l.id).collect();
for format in [Format::Svg, Format::Drawio] {
for background in [false, true] {
for placeholders in [false, true] {
let text = exchange::export(
&project,
&ids,
format,
Options {
background,
placeholders,
},
)
.unwrap();
let doc = parse_values(&text).unwrap();
assert_eq!(
doc.shapes.iter().filter(|s| s.background_only).count(),
usize::from(background)
);
let shapes: Vec<_> = doc.shapes.iter().filter(|s| !s.background_only).collect();
assert_eq!(shapes.len(), ids.len());
let mut imported = Layout::default();
let mappings: Vec<_> = shapes
.iter()
.enumerate()
.map(|(i, s)| {
let g = project.layers[i].bounds;
let expected = Geometry {
x: g.x.round(),
y: g.y.round(),
width: g.width.round(),
height: g.height.round(),
};
assert_eq!(s.geometry, expected);
assert_eq!(s.outline, [0.0, 0.0]);
(Some(imported.layer_info(i).id), s.geometry, None)
})
.collect();
imported.import_device_layers(&mappings).unwrap();
let reexport = exchange::export(
&Project::from_layout(&imported),
&ids,
format,
Options {
background,
placeholders,
},
)
.unwrap();
let reread = parse_values(&reexport).unwrap();
assert_eq!(
reread
.shapes
.iter()
.filter(|s| !s.background_only)
.map(|s| s.geometry)
.collect::<Vec<_>>(),
shapes.iter().map(|s| s.geometry).collect::<Vec<_>>()
);
}
}
}
}
#[test]
fn single_full_screen_layer_is_never_mistaken_for_background() {
let mut p = Project::from_layout(&Layout::default());
p.layers[0].bounds = Geometry {
x: 0.0,
y: 0.0,
width: 1920.0,
height: 1080.0,
};
for format in [Format::Svg, Format::Drawio] {
for placeholders in [false, true] {
let text = exchange::export(
&p,
&[p.layers[0].id],
format,
Options {
background: true,
placeholders,
},
)
.unwrap();
let doc = parse_values(&text).unwrap();
assert_eq!(doc.shapes.len(), 2);
assert!(doc.shapes[0].background_only);
assert!(!doc.shapes[1].background);
assert!(!doc.shapes[1].background_only);
}
}
}
#[test]
fn drawio_compressed_resave_and_percent_encoded_clipboard_are_supported() {
let p = fixture();
let xml = exchange::export(
&p,
&[p.layers[0].id],
Format::Drawio,
Options {
background: true,
placeholders: true,
},
)
.unwrap();
let doc = roxmltree::Document::parse(&xml).unwrap();
let model = doc
.descendants()
.find(|n| n.has_tag_name("mxGraphModel"))
.unwrap();
let model = &xml[model.range()];
let encoded = model
.bytes()
.map(|b| format!("%{b:02X}"))
.collect::<String>();
let mut encoder =
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(encoded.as_bytes()).unwrap();
let compressed = STANDARD.encode(encoder.finish().unwrap());
let wrapped = format!("<mxfile><diagram>{compressed}</diagram></mxfile>");
for text in [&xml, &wrapped, &encoded] {
let shapes = parse_values(text).unwrap().shapes;
assert_eq!(shapes.len(), 2);
assert!(shapes[0].background_only);
assert_eq!(shapes[1].geometry.x, -13.0);
}
}
#[test]
fn reference_image_is_embedded_and_missing_ids_or_invalid_versions_fail() {
let mut p = fixture();
let mut png = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255]))
.write_to(&mut png, image::ImageFormat::Png)
.unwrap();
p.reference = Some(midra_layout::project::Reference {
name: "red".into(),
image_base64: STANDARD.encode(png.into_inner()),
visible: true,
opacity: 1.0,
preserve_ratio: false,
native_size: false,
offset: [0.0, 0.0],
});
let xml = exchange::export(
&p,
&[p.layers[0].id],
Format::Svg,
Options {
background: true,
placeholders: false,
},
)
.unwrap();
let doc = roxmltree::Document::parse(&xml).unwrap();
let data = doc
.descendants()
.find(|n| n.has_tag_name("image"))
.unwrap()
.attribute(("http://www.w3.org/1999/xlink", "href"))
.unwrap();
let bytes = STANDARD
.decode(data.strip_prefix("data:image/png;base64,").unwrap())
.unwrap();
let image = image::load_from_memory(&bytes).unwrap().to_rgba8();
assert_eq!(*image.get_pixel(0, 0), image::Rgba([255, 0, 0, 255]));
assert!(parse_values(&xml.replace("geometry=\"2\"", "geometry=\"99\"")).is_err());
assert!(exchange::export(&p, &[], Format::Svg, Options::default()).is_err());
assert!(exchange::export(&p, &[999], Format::Drawio, Options::default()).is_err());
assert!(exchange::export(&p, &[1, 1], Format::Svg, Options::default()).is_err());
assert!(parse_values("<mxfile><diagram/><diagram/></mxfile>").is_err());
assert!(parse_values("<mxfile><diagram>garbage</diagram></mxfile>").is_err());
}
#[test]
fn documented_examples_import_and_limits_are_enforced() {
for text in [
include_str!("../../../docs/interfaces/midra-layout-svg-v2.example.svg"),
include_str!("../../../docs/interfaces/midra-layout-drawio-v1.example.drawio"),
] {
let doc = parse_values(text).unwrap();
assert_eq!(doc.shapes.len(), 2);
assert!(doc.shapes.iter().all(|s| !s.background_only));
}
assert!(
parse_values(&"x".repeat(exchange::MAX_EXCHANGE_BYTES + 1))
.unwrap_err()
.contains("16 MiB")
);
let mut p = fixture();
p.layers[0].bounds.width = 0.1;
assert!(exchange::export(&p, &[p.layers[0].id], Format::Svg, Options::default()).is_err());
}

View File

@ -0,0 +1,4 @@
<mxfile host="Midra Layout" compressed="false"><diagram id="midra-layout" name="Layout"><mxGraphModel page="1" pageScale="1" pageWidth="1920" pageHeight="1080" grid="0" adaptiveColors="none" data-midra-layout-geometry="1"><root><mxCell id="0"/><mxCell id="1" parent="0"/>
<mxCell id="layer-2" value="Slides" data-midra-role="layer" vertex="1" parent="1" style="rounded=0;whiteSpace=wrap;html=0;strokeColor=none;fillColor=#173b50;fontColor=#ffffff;"><mxGeometry x="120" y="180" width="640" height="360" as="geometry"/></mxCell>
<mxCell id="layer-1" value="Presenter" data-midra-role="layer" vertex="1" parent="1" style="rounded=0;whiteSpace=wrap;html=0;strokeColor=none;fillColor=#173b50;fontColor=#ffffff;"><mxGeometry x="1160" y="180" width="640" height="360" as="geometry"/></mxCell>
</root></mxGraphModel></diagram></mxfile>

View File

@ -0,0 +1,124 @@
# Midra Layout SVG and draw.io exchange
The Export menu writes **SVG geometry v2** and **draw.io geometry v1**. Project
JSON remains version 9 and is the full-fidelity save format. These exchanges
preserve layer **visible-box geometry**, not sources, crop settings, zoom, pivots,
Midra links, locks, visibility, camera or selection. Pictures illustrate current
cropping; importing a picture does not reconstruct its crop or source settings.
## Scope, coordinates and artwork
Both formats offer Current layer (exactly one selected), Selected layers,
Specific layer (including hidden), All layers and Visible layers only. Stable IDs
are `layer-N`; order is document stacking order, independent of selection order.
All chosen layers are exported visibly, even if hidden in the editor. No layers,
unknown/duplicate IDs, invalid project geometry or dimensions rounding below one
pixel reject export. X/Y are top-left output pixels, relative to the **whole output
screen**, including for single-layer exports. X, Y, width and height round
independently to nearest integer; halves round away from zero. Negative positions
are retained. No stroke expansion is necessary: exported boxes have no outline.
Options are shared by the SVG/draw.io menus for the current session, default off;
they do not modify the project/settings schema:
- **Include background layer** adds a first, full-screen image with ID
`midra-background`, explicitly marked as background. A visible reference is
composited over a dark backdrop using the current fit/stretch/native-size,
offset and opacity. Otherwise it is a plain dark backdrop. This is a baked visual
reference, not an editable copy of reference settings. Image raster dimensions
are proportional to the screen, capped at 1920 pixels on the longest side;
the exported shape still has the exact screen dimensions.
- **Include placeholder pictures** uses embedded PNG source-grid patterns instead
of flat layer fills. The pattern reflects native input cropping and advanced
cropping, fitted into each visible box. Each raster is capped at 512 pixels on
its longest side. No live source image is available/captured by this exporter.
The images contain no external URLs and need no network access. Imported picture
layers are still geometry-only. Without this option, the layers are rectangles.
The background is detected and ignored by default on import and cannot be mapped
as a content layer. A legitimate full-screen layer is kept as a layer. Every
placeholder is **one** importable layer, not an image plus duplicate rectangle.
## SVG v2
Example: [midra-layout-svg-v2.example.svg](midra-layout-svg-v2.example.svg).
UTF-8 SVG; SVG namespace and optional XLink namespace. Root attributes:
- `data-midra-layout-geometry="2"`
- `width`, `height`: output screen dimensions in pixels
- `viewBox="0 0 W H"`
Each layer is a `<rect>` (plain) or `<image>` (placeholder), with `id="layer-N"`,
`data-midra-role="layer"`, `x`, `y`, `width`, `height`. A `<title>` carries its name
for external viewers; Midra import does not rename destinations. Images use
`xlink:href="data:image/png;base64,..."` and `preserveAspectRatio="none"`.
The optional background is an `<image>` with `data-midra-role="background"` and
full-page bounds. No visible text geometry, transforms, clipping or CSS is needed.
The importer supports v1 and v2 and explicitly rejects other marked versions.
Legacy `Project::to_svg`/`to_svg_ids` continue producing v1 rectangle-only SVG;
the GUI uses v2. Old applications cannot import v2 placeholder images; use JSON
or a plain rectangle-only export where required. Editors should retain role
markers. If they remove them, ordinary image import remains intentionally limited
to a first full-page background. Midra never fetches image URLs during import.
## draw.io v1
Example: [midra-layout-drawio-v1.example.drawio](midra-layout-drawio-v1.example.drawio).
UTF-8 uncompressed `<mxfile compressed="false">` with one `<diagram>` containing
an `<mxGraphModel data-midra-layout-geometry="1">`. `pageWidth`, `pageHeight`,
`pageScale="1"`, and `page="1"` establish the output canvas; diagram units are pixels.
Root cells `0` and `1` provide the required graph root and default layer.
Each exported shape is an `<mxCell vertex="1" parent="1">` with stable `id`,
escaped plain-text `value` (layer name), and `data-midra-role="layer"` or
`"background"`. Its single `<mxGeometry as="geometry">` stores pixel X/Y/width/
height. Styles disable outlines and rounding. Pictures use `shape=image`,
`imageAspect=0`, and draw.io's `image=data:image/png,BASE64` style syntax (without
`;base64`, which would split the style). Background label text is empty.
Import accepts raw/once-percent-encoded mxGraphModel clipboard XML, single-page
mxfile XML, and native compressed diagram text: Base64 → raw DEFLATE → percent
decode → mxGraphModel. Native re-saving may remove the model's Midra version
attribute; role attributes and stable IDs survive in the tested version. The
reserved `midra-background` ID also identifies the exported background. Unknown
marked draw.io exchange versions are rejected. Multiple pages are refused with an
instruction to export one page, rather than silently importing the wrong page.
Groups, edges, rotation, flips, relative/alternate bounds and nonrectangular
shapes remain unsupported; ordinary unrotated image cells now import their box.
## Limits, import and round trips
Import files and clipboard text, and generated exports, are capped at **16 MiB**
(to allow self-contained images). Decompression is bounded: at most 48 MiB of
percent-encoded text and 16 MiB decoded XML. Up to 256 layer boxes plus one
background are allowed. No imported image is decoded or downloaded by the
geometry importer. Export reference decoding retains the existing 8192-pixel
per-side/256 MiB decoder bounds. Oversized exports fail before writing a file.
Use **Import → SVG / draw.io file…**, or paste XML, then review and map shapes to
editor layers. Destination count need not match current selection. Import with
size and position enabled restores the rounded geometry in one Undo step. Output
screen resolution is not imported. Mapped names, sources and Midra links stay with
the destination layers. File replacement retains the existing explicit overwrite
confirmation and atomic-write path.
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.
A manual native-editor check is available:
```sh
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
cargo run --locked -p midra-layout --example check_geometry_exchange -- verify /tmp/midra-exchange-check/resaved.xml
```
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
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/)
and [desktop CLI](https://github.com/jgraph/drawio/wiki/Desktop-App).

View File

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" data-midra-layout-geometry="2" width="1920" height="1080" viewBox="0 0 1920 1080">
<title>Midra Layout geometry</title>
<rect id="layer-2" data-midra-role="layer" x="120" y="180" width="640" height="360" fill="#173b50"><title>Slides</title></rect>
<rect id="layer-1" data-midra-role="layer" x="1160" y="180" width="640" height="360" fill="#173b50"><title>Presenter</title></rect>
</svg>

After

Width:  |  Height:  |  Size: 470 B

View File

@ -141,18 +141,21 @@ by editor IDs. Selection stores stable layer IDs, not zero-based indices. At
least one layer must remain. Visibility and locks remain local protection flags and are undoable.
SVG export supports all, visible-only, explicit specific-layer (including hidden)
or selected layers (including a single
layer); rectangles retain stable IDs and document stacking order. Names/folders
are not added to the geometry SVG format.
layer); rectangles retain stable IDs and document stacking order. Names appear as titles/labels in current geometry exchanges; folders are omitted.
Reordering changes only the order of the existing `layers` array, not IDs or
per-layer values. Reordering uses the existing array order; SVG remains v1. Moving layer 1 above
per-layer values. Reordering uses the existing array order for every exchange version. Moving layer 1 above
layer 2 in the list saves IDs in `[2, 1]` order and emits `layer-2` before `layer-1` in SVG.
Loading preserves that order; selected-layer exports still follow document order,
not selection order. Source slots, `next_layer_id`, names, folders, crop geometry,
visibility/locks and Midra links remain attached to their original layer IDs.
The inspector and layer manager display the reverse of document order: top row is topmost. Selection does not raise a layer; canvas drawing and hit testing follow the saved stack.
## SVG geometry exchange, version 1
## Legacy SVG geometry exchange, version 1
The Export menu now produces SVG v2 and draw.io v1 with optional artwork; see
[geometry exchange](midra-layout-exchange.md) for their current contracts and
examples. The v1 API below remains readable and available for compatibility.
Suggested filename: `layout.svg`. UTF-8 SVG with SVG namespace, `width`, `height`
and `viewBox="0 0 W H"` equal to the output screen. The root carries
@ -189,7 +192,7 @@ and `viewBox="0 0 W H"` equal to the output screen. The root carries
## Compatibility changes
Project version 9 and SVG version 1 are strict contracts. A breaking project field/meaning change must bump
Project version 9 and the versioned SVG/draw.io exchanges are strict contracts. A breaking project field/meaning change must bump
`version` and either implement a tested migration or clearly reject older/newer
files. Changing rectangle/marker semantics requires a corresponding documented
SVG interface revision and importer tests. Update this document and its example

View File

@ -534,6 +534,14 @@ and Centered-crop import round trips passed Eikos 3.3.10 hardware checks.
## Pending stretch goals — specifications to follow
- [ ] **More software export/import formats.** Extend the SVG/draw.io exchange to
additional graphics and layout applications (for example Inkscape/Illustrator
workflows and other formats as specified). For each adapter, define supported
geometry, optional background and placeholder-image capabilities, and validate
round trips through the target application. Document losses and versioned
interfaces; unsupported image features should be unavailable rather than implied.
- [ ] **Capture Midra input preview images.** Capture a still preview from a chosen
Midra input for inspecting source content and framing in the editor. Verify on
the target firmware whether WebRCS exposes previews on request or continuously,

View File

@ -4,7 +4,7 @@
A native Rust/egui workspace for positioning rectangular layers, with offline editing
and an explicit Eikos 4K device link.
Select layers, paste draw.io or import SVG geometry, move them visually or enter exact corner
Select layers, paste or import draw.io/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.
Connection reads and reviewed device sends happen only on request.
@ -13,15 +13,15 @@ Connection reads and reviewed device sends happen only on request.
cargo run --locked -p midra-layout
```
## Paste layer values and import SVG
## Paste layer values and import SVG / draw.io
1. Choose destinations using **Choose destination layers…** in the Import menu
or review window. Selecting them on the canvas or right-hand list also works
(Shift-click for multiple layers).
2. Copy layer values in Midra Layout or 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 file…** opens an SVG file in the
same review window; raw SVG XML can also be pasted. **Import → Clipboard values**
area and click **Read geometry**. **Import → SVG / draw.io file…** opens an SVG or draw.io file in the
same review window; raw SVG/draw.io XML can also be pasted. **Import → Clipboard values**
reads the clipboard directly and opens the mapping review.
3. Review each detected rectangle and choose its destination layer. With nothing
selected, each rectangle's dropdown lists all editor layers (hidden/locked
@ -60,16 +60,18 @@ A first full-page rectangle or image is marked as a possible background. Check
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,
Midra SVG v2 placeholder images import as one layer box each; their image content
is not decoded. 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
styles for predictable results. Files are limited to 16 MiB, 256 rectangles plus an optional background, 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 draw.io adapter accepts single-page `.drawio`/`.xml` files (including native
compression) and raw or once-percent-encoded `mxGraphModel` clipboard XML, like
[the supplied clipboard fixture](../crates/midra-layout/tests/fixtures/drawio-rectangle.txt).
Draw.io coordinates map **1:1 to screen pixels**, with a top-left origin. This is
an explicit import convention; no page-scale, physical-unit or viewport-size
@ -101,7 +103,7 @@ appearance settings. It currently rejects grouped/nested geometry, connections,
nonrectangular shapes, relative coordinates, alternate bounds, rotated/flipped
objects, named/inherited styles, wrapped objects and compressed `.drawio` files.
Mixed selections containing unsupported objects are rejected as a whole. Invalid
input makes no document changes. Text is limited to 1 MiB; geometry must have
input makes no document changes. Text is limited to 16 MiB; geometry must have
finite coordinates within ±1,000,000 px and positive sizes up to 1,000,000 px.
These are application limits, not verified Eikos limits.
@ -550,15 +552,20 @@ viewport preferences, and the embedded reference image. Apply pending edits
before saving. Opening asks before replacing current work and starts a fresh
undo history. Existing files require confirmation before replacement.
**Project → Export → Export SVG** offers **All layers** and **Visible layers only**.
These exports contain whole-pixel layer boxes. Import them with **Import → SVG
file** and map the detected rectangles to the same number of selected layers.
SVG exchanges geometry; JSON preserves the complete project, including crops
and the reference image.
**Project → Export → Export SVG / Export draw.io** offers **Current layer…**,
**Selected layers…**, **Specific layer…**, **All layers…** and **Visible layers
only…**. A current-layer export keeps its original screen position and full-screen
canvas. Both menus offer **Include background layer** (visible reference or plain
backdrop) and **Include placeholder pictures** (source-grid imagery reflecting
cropping). Images are embedded and require no external files.
The [save/export interface specification](interfaces/midra-layout.md) documents
both formats, their limitations, validation, and compatibility policy, with a
[complete JSON example](interfaces/midra-layout-v1.example.json).
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
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).
Visual crop mode also provides **Reset crop** beside **Done adjusting crop** in
layer properties. It restores 100% content zoom and centered offsets, keeps the
@ -720,7 +727,7 @@ Stable IDs survive removal and are independent of Midra layer numbers. Group
movement, alignment and Same-handles resizing work across the selection;
Mirror/Opposite resizing still require exactly two layers.
Project JSON is now version 4, with tested migration from versions 1–3.
Project JSON is version 9, with tested migration from older supported versions.
**Project → Export → Export SVG → Selected layers…** exports just the current selection,
including a single layer. All/visible export remains available.

View File

@ -4,6 +4,8 @@
## Unreleased
- 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.
- Constrain Crop-tab X/Y offsets to the valid content bounds, including after zoom decreases; typed and dragged edits clamp to the edge instead of producing offset-range errors. Undo remains available.