Add optional Midra parameter snapshots to compatible exports
This commit is contained in:
parent
3fdb9879ad
commit
f14e5e65bf
|
|
@ -2817,6 +2817,7 @@ dependencies = [
|
|||
"tempfile",
|
||||
"tungstenite",
|
||||
"winresource",
|
||||
"zip 2.6.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ vendor_formats = ["dep:craft-dwg", "dep:deckcraft-pptx", "dep:deckcraft-model",
|
|||
no_proprietary = []
|
||||
|
||||
[dependencies]
|
||||
zip = { version = "2", default-features = false, features = ["deflate"] }
|
||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "79e97b6febcb62de406e5bcf5a724bd3f7333065" }
|
||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "79e97b6febcb62de406e5bcf5a724bd3f7333065", optional = true }
|
||||
deckcraft-pptx = { version = "=0.6.1", optional = true }
|
||||
|
|
|
|||
|
|
@ -40,6 +40,7 @@ fn main() -> Result<(), String> {
|
|||
&ids,
|
||||
codec,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: pictures,
|
||||
},
|
||||
|
|
@ -83,12 +84,14 @@ fn main() -> Result<(), String> {
|
|||
(
|
||||
"illustrated",
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: true,
|
||||
},
|
||||
),
|
||||
] {
|
||||
let options = Options {
|
||||
extra_parameters: false,
|
||||
placeholders: options.placeholders && format.supports_placeholders(),
|
||||
..options
|
||||
};
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ pub enum Format {
|
|||
}
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Options {
|
||||
pub extra_parameters: bool,
|
||||
pub background: bool,
|
||||
pub placeholders: bool,
|
||||
}
|
||||
|
|
@ -172,7 +173,24 @@ pub fn export(
|
|||
let shapes = prepare_shapes(project, ids, options, format.supports_placeholders())?;
|
||||
let w = project.output_resolution.width;
|
||||
let h = project.output_resolution.height;
|
||||
encode_shapes(format, [w, h], &shapes)
|
||||
let text = encode_shapes(format, [w, h], &shapes)?;
|
||||
if options.extra_parameters {
|
||||
let codec = match format {
|
||||
Format::Svg => crate::interchange::Codec::Svg,
|
||||
Format::Drawio => crate::interchange::Codec::Drawio,
|
||||
Format::Json => crate::interchange::Codec::Json,
|
||||
Format::Csv => crate::interchange::Codec::Csv,
|
||||
Format::Dxf => crate::interchange::Codec::Dxf,
|
||||
Format::Html => crate::interchange::Codec::Html,
|
||||
};
|
||||
let bytes = crate::exchange_metadata::embed(text.into_bytes(), codec, project, ids)?;
|
||||
if bytes.len() > MAX_EXCHANGE_BYTES {
|
||||
return Err("Export exceeds 16 MiB.".into());
|
||||
}
|
||||
String::from_utf8(bytes).map_err(|e| e.to_string())
|
||||
} else {
|
||||
Ok(text)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_shapes(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,347 @@
|
|||
//! Optional, inert project snapshots carried by geometry files.
|
||||
use crate::{interchange::Codec, project::Project};
|
||||
use base64::{Engine, engine::general_purpose::STANDARD};
|
||||
use std::io::{Cursor, Read, Write};
|
||||
|
||||
pub const KEY: &str = "beffroi_midra_parameters";
|
||||
const MAX_METADATA: usize = 1024 * 1024;
|
||||
const PREFIX: &str = "beffroi-midra-parameters:";
|
||||
|
||||
pub fn supported(codec: Codec) -> bool {
|
||||
!matches!(codec, Codec::Dwg | Codec::Figma | Codec::Illustrator)
|
||||
}
|
||||
|
||||
/// Exclude unexported layers, unused inputs, image bytes and device capture bindings.
|
||||
pub fn snapshot(project: &Project, ids: &[usize]) -> Result<Project, String> {
|
||||
project.layout()?;
|
||||
let mut p = project.clone();
|
||||
p.layers.retain(|l| ids.contains(&l.id));
|
||||
p.editor.selected_layer_ids.retain(|id| ids.contains(id));
|
||||
p.references.clear();
|
||||
p.workspace.previews.clear();
|
||||
p.workspace
|
||||
.collapsed_folders
|
||||
.retain(|f| p.layers.iter().any(|l| &l.folder == f));
|
||||
p.inputs
|
||||
.retain(|s| p.layers.iter().any(|l| l.source_id == s.id));
|
||||
for (i, source) in p.inputs.iter_mut().enumerate() {
|
||||
for layer in &mut p.layers {
|
||||
if layer.source_id == source.id {
|
||||
layer.source_id = i + 1;
|
||||
}
|
||||
}
|
||||
source.id = i + 1;
|
||||
}
|
||||
p.layout()?;
|
||||
Ok(p)
|
||||
}
|
||||
fn encode(project: &Project, ids: &[usize]) -> Result<String, String> {
|
||||
let json = snapshot(project, ids)?.to_json()?;
|
||||
if json.len() > MAX_METADATA {
|
||||
return Err("Extra parameters exceed 1 MiB.".into());
|
||||
}
|
||||
Ok(STANDARD.encode(json))
|
||||
}
|
||||
fn decode(encoded: &str) -> Result<Project, String> {
|
||||
if encoded.len() > MAX_METADATA * 4 / 3 + 4 {
|
||||
return Err("Extra parameters exceed 1 MiB.".into());
|
||||
}
|
||||
let bytes = STANDARD
|
||||
.decode(encoded)
|
||||
.map_err(|e| format!("Invalid extra parameters: {e}"))?;
|
||||
let text = std::str::from_utf8(&bytes).map_err(|e| e.to_string())?;
|
||||
Project::from_json(text)
|
||||
}
|
||||
|
||||
pub(crate) fn embed(
|
||||
bytes: Vec<u8>,
|
||||
codec: Codec,
|
||||
project: &Project,
|
||||
ids: &[usize],
|
||||
) -> Result<Vec<u8>, String> {
|
||||
if !supported(codec) {
|
||||
return Err("Extra parameters are not supported by this format's current codec.".into());
|
||||
}
|
||||
let payload = encode(project, ids)?;
|
||||
if codec == Codec::Pptx {
|
||||
return embed_pptx(&bytes, &payload);
|
||||
}
|
||||
let mut text = String::from_utf8(bytes).map_err(|e| e.to_string())?;
|
||||
match codec {
|
||||
Codec::Svg => {
|
||||
let at = text.rfind("</svg>").ok_or("Missing SVG root")?;
|
||||
text.insert_str(at, &format!("<metadata><parameters xmlns=\"urn:beffroi:midra:parameters:1\">{payload}</parameters></metadata>\n"));
|
||||
}
|
||||
Codec::Drawio => {
|
||||
// Global custom properties live on the root cell's UserObject.
|
||||
text = text.replacen(
|
||||
"<mxCell id=\"0\"/>",
|
||||
&format!("<object id=\"0\" {KEY}=\"{payload}\"><mxCell/></object>"),
|
||||
1,
|
||||
);
|
||||
}
|
||||
Codec::Html => {
|
||||
let at = text.find("</head>").ok_or("Missing HTML head")?;
|
||||
text.insert_str(
|
||||
at,
|
||||
&format!("<meta name=\"{KEY}\" content=\"{payload}\"/>\n"),
|
||||
);
|
||||
}
|
||||
Codec::Json => {
|
||||
let mut value: serde_json::Value =
|
||||
serde_json::from_str(&text).map_err(|e| e.to_string())?;
|
||||
value["version"] = 2.into();
|
||||
value[KEY] = payload.into();
|
||||
text = serde_json::to_string_pretty(&value).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Codec::Csv => {
|
||||
text = csv_metadata(&text, Some(&payload))?;
|
||||
}
|
||||
Codec::Dxf => {
|
||||
let mut comments = String::new();
|
||||
for chunk in payload.as_bytes().chunks(200) {
|
||||
comments.push_str(&format!(
|
||||
"999\n{PREFIX}{}\n",
|
||||
std::str::from_utf8(chunk).unwrap()
|
||||
));
|
||||
}
|
||||
let at = text.split_inclusive('\n').take(2).map(str::len).sum();
|
||||
text.insert_str(at, &comments);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Ok(text.into_bytes())
|
||||
}
|
||||
|
||||
fn csv_metadata(text: &str, payload: Option<&str>) -> Result<String, String> {
|
||||
let mut reader = csv::Reader::from_reader(text.as_bytes());
|
||||
let header = reader.headers().map_err(|e| e.to_string())?.clone();
|
||||
let extra = header.iter().position(|v| v == KEY);
|
||||
let version = header
|
||||
.iter()
|
||||
.position(|v| v == "midra_geometry_version")
|
||||
.ok_or("Missing CSV version")?;
|
||||
let mut writer = csv::WriterBuilder::new()
|
||||
.terminator(csv::Terminator::CRLF)
|
||||
.from_writer(Vec::new());
|
||||
let mut out: Vec<_> = header
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| Some(*i) != extra)
|
||||
.map(|(_, v)| v.to_string())
|
||||
.collect();
|
||||
if payload.is_some() {
|
||||
out.push(KEY.into());
|
||||
}
|
||||
writer.write_record(out).map_err(|e| e.to_string())?;
|
||||
for (row, record) in reader.records().enumerate() {
|
||||
let record = record.map_err(|e| e.to_string())?;
|
||||
let expected = if payload.is_some() { "1" } else { "2" };
|
||||
if record.get(version) != Some(expected) {
|
||||
return Err("Unsupported metadata CSV version.".into());
|
||||
}
|
||||
let mut out: Vec<_> = record
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| Some(*i) != extra)
|
||||
.map(|(i, v)| {
|
||||
if i == version {
|
||||
if payload.is_some() {
|
||||
"2".into()
|
||||
} else {
|
||||
"1".into()
|
||||
}
|
||||
} else {
|
||||
v.to_string()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if let Some(payload) = payload {
|
||||
out.push(if row == 0 {
|
||||
payload.into()
|
||||
} else {
|
||||
String::new()
|
||||
});
|
||||
}
|
||||
writer.write_record(out).map_err(|e| e.to_string())?;
|
||||
}
|
||||
String::from_utf8(writer.into_inner().map_err(|e| e.to_string())?).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Strip only the known v2 extension before the existing strict geometry parser.
|
||||
/// Bad optional metadata must not prevent ordinary geometry import.
|
||||
pub(crate) fn geometry_text(text: &str) -> Result<Option<String>, String> {
|
||||
if text.trim_start().starts_with('{') {
|
||||
let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| e.to_string())?;
|
||||
if value["format"] == "beffroi.midra-geometry" && value["version"] == 2 {
|
||||
if value.as_object_mut().unwrap().remove(KEY).is_none() {
|
||||
return Err("Geometry JSON v2 requires extra parameters.".into());
|
||||
}
|
||||
value["version"] = 1.into();
|
||||
return serde_json::to_string(&value)
|
||||
.map(Some)
|
||||
.map_err(|e| e.to_string());
|
||||
}
|
||||
} else if text
|
||||
.lines()
|
||||
.next()
|
||||
.is_some_and(|h| h.contains(KEY) && h.contains("midra_geometry_version"))
|
||||
{
|
||||
return csv_metadata(text, None).map(Some);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Restore the original exported snapshot explicitly; never overwrite edited geometry implicitly.
|
||||
pub fn extract(bytes: &[u8], codec: Codec) -> Result<Option<Project>, String> {
|
||||
if bytes.len() > crate::exchange::MAX_EXCHANGE_BYTES {
|
||||
return Err("Import exceeds 16 MiB.".into());
|
||||
}
|
||||
if !supported(codec) {
|
||||
return Ok(None);
|
||||
}
|
||||
let payload = if codec == Codec::Pptx {
|
||||
let mut zip = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| e.to_string())?;
|
||||
let text = match zip.by_name("docProps/custom.xml") {
|
||||
Ok(file) => read_bounded(file)?,
|
||||
Err(zip::result::ZipError::FileNotFound) => return Ok(None),
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
let xml = roxmltree::Document::parse(&text).map_err(|e| e.to_string())?;
|
||||
xml.descendants()
|
||||
.find(|n| n.has_tag_name("property") && n.attribute("name") == Some(KEY))
|
||||
.and_then(|n| n.children().find(|c| c.has_tag_name("lpwstr")))
|
||||
.and_then(|n| n.text())
|
||||
.map(str::to_owned)
|
||||
} else {
|
||||
let text = std::str::from_utf8(bytes).map_err(|e| e.to_string())?;
|
||||
match codec {
|
||||
Codec::Json => serde_json::from_str::<serde_json::Value>(text)
|
||||
.map_err(|e| e.to_string())?[KEY]
|
||||
.as_str()
|
||||
.map(str::to_owned),
|
||||
Codec::Csv => {
|
||||
let mut reader = csv::Reader::from_reader(bytes);
|
||||
let index = reader
|
||||
.headers()
|
||||
.map_err(|e| e.to_string())?
|
||||
.iter()
|
||||
.position(|v| v == KEY);
|
||||
match index {
|
||||
None => None,
|
||||
Some(i) => {
|
||||
let mut payload = None;
|
||||
for row in reader.records() {
|
||||
let row = row.map_err(|e| e.to_string())?;
|
||||
if let Some(value) = row.get(i).filter(|v| !v.is_empty()) {
|
||||
if payload.is_some() {
|
||||
return Err("Multiple extra-parameter snapshots in CSV.".into());
|
||||
}
|
||||
payload = Some(value.to_string());
|
||||
}
|
||||
}
|
||||
payload
|
||||
}
|
||||
}
|
||||
}
|
||||
Codec::Dxf => {
|
||||
let lines: Vec<_> = text.lines().collect();
|
||||
let payload: String = lines
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.filter(|p| p[0].trim() == "999")
|
||||
.filter_map(|p| p[1].strip_prefix(PREFIX))
|
||||
.collect();
|
||||
(!payload.is_empty()).then_some(payload)
|
||||
}
|
||||
_ => {
|
||||
let xml = roxmltree::Document::parse_with_options(
|
||||
text,
|
||||
roxmltree::ParsingOptions {
|
||||
allow_dtd: true,
|
||||
nodes_limit: 200_000,
|
||||
},
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let direct = xml
|
||||
.descendants()
|
||||
.find_map(|n| {
|
||||
if n.has_tag_name(("urn:beffroi:midra:parameters:1", "parameters")) {
|
||||
n.text()
|
||||
} else if n.has_tag_name("meta") && n.attribute("name") == Some(KEY) {
|
||||
n.attribute("content")
|
||||
} else {
|
||||
n.attribute(KEY)
|
||||
}
|
||||
})
|
||||
.map(str::to_owned);
|
||||
if direct.is_some() {
|
||||
direct
|
||||
} else if codec == Codec::Drawio
|
||||
|| (codec == Codec::Svg && xml.root_element().attribute("content").is_some())
|
||||
{
|
||||
let model = crate::drawio_model(
|
||||
xml.root_element().attribute("content").unwrap_or(text),
|
||||
)?;
|
||||
let model = roxmltree::Document::parse(&model).map_err(|e| e.to_string())?;
|
||||
model
|
||||
.descendants()
|
||||
.find_map(|n| n.attribute(KEY))
|
||||
.map(str::to_owned)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
payload.map(|p| decode(&p)).transpose()
|
||||
}
|
||||
fn read_bounded(reader: impl Read) -> Result<String, String> {
|
||||
let mut text = String::new();
|
||||
reader
|
||||
.take((MAX_METADATA * 2 + 1) as u64)
|
||||
.read_to_string(&mut text)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if text.len() > MAX_METADATA * 2 {
|
||||
return Err("Metadata part exceeds 2 MiB.".into());
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
fn embed_pptx(bytes: &[u8], payload: &str) -> Result<Vec<u8>, String> {
|
||||
let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| e.to_string())?;
|
||||
let mut writer = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
let options = zip::write::SimpleFileOptions::default()
|
||||
.compression_method(zip::CompressionMethod::Deflated);
|
||||
for i in 0..archive.len() {
|
||||
let mut file = archive.by_index(i).map_err(|e| e.to_string())?;
|
||||
let name = file.name().to_string();
|
||||
if name == "docProps/custom.xml" {
|
||||
return Err("Exporter already contains custom properties.".into());
|
||||
}
|
||||
if name == "[Content_Types].xml" || name == "_rels/.rels" {
|
||||
let text = read_bounded(&mut file)?;
|
||||
let text = if name == "[Content_Types].xml" {
|
||||
text.replace("</Types>", "<Override PartName=\"/docProps/custom.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.custom-properties+xml\"/></Types>")
|
||||
} else {
|
||||
text.replace("</Relationships>", "<Relationship Id=\"rIdMidraParameters\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties\" Target=\"docProps/custom.xml\"/></Relationships>")
|
||||
};
|
||||
writer
|
||||
.start_file(name, options)
|
||||
.map_err(|e| e.to_string())?;
|
||||
writer
|
||||
.write_all(text.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
writer.raw_copy_file(file).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
writer
|
||||
.start_file("docProps/custom.xml", options)
|
||||
.map_err(|e| e.to_string())?;
|
||||
write!(writer, "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties\" xmlns:vt=\"http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes\"><property fmtid=\"{{D5CDD505-2E9C-101B-9397-08002B2CF9AE}}\" pid=\"2\" name=\"{KEY}\"><vt:lpwstr>{payload}</vt:lpwstr></property></Properties>").map_err(|e| e.to_string())?;
|
||||
writer
|
||||
.finish()
|
||||
.map(|c| c.into_inner())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
|
@ -6700,6 +6700,7 @@ mod tests {
|
|||
&ids,
|
||||
format,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: true,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -56,6 +56,9 @@ pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
|
|||
if text.len() > crate::exchange::MAX_EXCHANGE_BYTES {
|
||||
return Err("Import text exceeds 16 MiB.".into());
|
||||
}
|
||||
if let Some(geometry) = crate::exchange_metadata::geometry_text(text)? {
|
||||
return parse_values(&geometry);
|
||||
}
|
||||
if text.contains(" — visible box (device container unverified)") {
|
||||
return parse_midra_values(text);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -124,6 +124,9 @@ pub fn export(
|
|||
"This build excludes vendor formats; rebuild with vendor_formats enabled.".into(),
|
||||
);
|
||||
}
|
||||
if options.extra_parameters && !crate::exchange_metadata::supported(codec) {
|
||||
return Err("Extra parameters are not supported by this format’s current codec.".into());
|
||||
}
|
||||
let shapes = exchange::prepare_shapes(project, ids, options, codec.artwork())?;
|
||||
let canvas = [
|
||||
project.output_resolution.width,
|
||||
|
|
@ -141,6 +144,11 @@ pub fn export(
|
|||
return Err("Vendor formats are unavailable in this build.".into());
|
||||
}
|
||||
};
|
||||
let bytes = if options.extra_parameters {
|
||||
crate::exchange_metadata::embed(bytes, codec, project, ids)?
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
if bytes.len() > exchange::MAX_EXCHANGE_BYTES {
|
||||
return Err("Export exceeds 16 MiB; disable artwork or export fewer layers.".into());
|
||||
}
|
||||
|
|
@ -187,3 +195,46 @@ pub fn import(bytes: &[u8], filename: &str) -> Result<Vec<Page>, String> {
|
|||
document: import::parse_values(text)?,
|
||||
}])
|
||||
}
|
||||
|
||||
/// Explicit recovery of extra parameters; the artwork path never becomes the save path.
|
||||
pub fn read_embedded_project(path: &std::path::Path) -> Result<Project, String> {
|
||||
use std::io::Read;
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)
|
||||
.map_err(|e| e.to_string())?
|
||||
.take(exchange::MAX_EXCHANGE_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let ext = path
|
||||
.extension()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
let codec = Codec::available()
|
||||
.into_iter()
|
||||
.find(|c| c.extension() == ext || (ext == "xml" && *c == Codec::Drawio))
|
||||
.ok_or("Unsupported extra-parameter format")?;
|
||||
crate::exchange_metadata::extract(&bytes, codec)?
|
||||
.ok_or("No supported Midra parameters found. Use geometry import for this file.".into())
|
||||
}
|
||||
|
||||
/// The boolean distinguishes a native project path from a recovered export snapshot.
|
||||
pub fn read_project_or_parameters(path: &std::path::Path) -> Result<(Project, bool), String> {
|
||||
use std::io::Read;
|
||||
let mut bytes = Vec::new();
|
||||
std::fs::File::open(path)
|
||||
.map_err(|e| e.to_string())?
|
||||
.take(crate::project::MAX_PROJECT_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > crate::project::MAX_PROJECT_BYTES {
|
||||
return Err("Project exceeds 96 MiB.".into());
|
||||
}
|
||||
if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
|
||||
&& value["format"] == crate::project::FORMAT
|
||||
{
|
||||
return Project::from_json(std::str::from_utf8(&bytes).map_err(|e| e.to_string())?)
|
||||
.map(|p| (p, true));
|
||||
}
|
||||
read_embedded_project(path).map(|p| (p, false))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ pub mod device_capture;
|
|||
pub mod device_send;
|
||||
use std::collections::HashMap;
|
||||
pub mod exchange;
|
||||
pub mod exchange_metadata;
|
||||
mod folders;
|
||||
pub mod formats;
|
||||
mod geometry_formats;
|
||||
|
|
@ -1853,6 +1854,22 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
|
|||
.ok_or("draw.io root is missing.")?;
|
||||
let mut cells = HashMap::new();
|
||||
for n in root.children().filter(|n| n.is_element()) {
|
||||
// draw.io stores global custom properties on a wrapped root cell.
|
||||
if matches!(n.tag_name().name(), "object" | "UserObject") && n.attribute("id") == Some("0")
|
||||
{
|
||||
let children: Vec<_> = n.children().filter(|c| c.is_element()).collect();
|
||||
if children.len() == 1
|
||||
&& children[0].has_tag_name("mxCell")
|
||||
&& ["vertex", "edge", "parent"]
|
||||
.iter()
|
||||
.all(|a| children[0].attribute(*a).is_none())
|
||||
{
|
||||
if cells.insert("0", children[0]).is_some() {
|
||||
return Err("Duplicate draw.io cell ID.".into());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if !n.has_tag_name("mxCell") {
|
||||
return Err("Wrapped objects are not supported yet. Copy plain rectangles.".into());
|
||||
}
|
||||
|
|
@ -1963,7 +1980,7 @@ pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
|
|||
}
|
||||
Ok(result)
|
||||
}
|
||||
fn drawio_model(xml: &str) -> Result<String, String> {
|
||||
pub(crate) 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}"))?;
|
||||
|
|
|
|||
|
|
@ -198,12 +198,13 @@ impl Editor {
|
|||
self.files.message = if recovery {
|
||||
None
|
||||
} else {
|
||||
Some(format!(
|
||||
"Opened {}",
|
||||
Some(
|
||||
path.as_ref()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_default()
|
||||
))
|
||||
.map(|p| format!("Opened {}", p.display()))
|
||||
.unwrap_or_else(|| {
|
||||
"Restored embedded parameters into an unsaved project.".into()
|
||||
}),
|
||||
)
|
||||
};
|
||||
self.files.project_path = path;
|
||||
self.files.manual_saved_at = time;
|
||||
|
|
@ -337,6 +338,18 @@ impl Editor {
|
|||
self.files.opening = Some(path);
|
||||
}
|
||||
}
|
||||
if ui.button("Restore parameters from export…").clicked() {
|
||||
ui.close_menu();
|
||||
if let Some(path) = rfd::FileDialog::new()
|
||||
.add_filter(
|
||||
"Exports with Midra parameters",
|
||||
&["svg", "drawio", "xml", "json", "csv", "dxf", "html", "pptx"],
|
||||
)
|
||||
.pick_file()
|
||||
{
|
||||
self.files.opening = Some(path);
|
||||
}
|
||||
}
|
||||
if ui.button("Save project…").clicked() {
|
||||
ui.close_menu();
|
||||
self.save_project_as();
|
||||
|
|
@ -371,6 +384,22 @@ impl Editor {
|
|||
}
|
||||
}
|
||||
fn exchange_menu(&mut self, ui: &mut egui::Ui, format: midra_layout::interchange::Codec) {
|
||||
let metadata = midra_layout::exchange_metadata::supported(format);
|
||||
if !metadata {
|
||||
self.files.exchange_options.extra_parameters = false;
|
||||
}
|
||||
ui.add_enabled(
|
||||
metadata,
|
||||
egui::Checkbox::new(
|
||||
&mut self.files.exchange_options.extra_parameters,
|
||||
"Include extra Midra parameters (experimental)",
|
||||
),
|
||||
);
|
||||
ui.small(if metadata {
|
||||
"Embeds the exported layers’ source/crop settings, names, folders, links and workspace settings. No image bytes or capture bindings. Other apps may remove it. Restore the original snapshot through Project → Restore parameters from export; geometry import still uses the artwork."
|
||||
} else {
|
||||
"Extra parameters are not yet supported for this format. Save a Midra project alongside it."
|
||||
});
|
||||
ui.checkbox(
|
||||
&mut self.files.exchange_options.background,
|
||||
"Include background layer",
|
||||
|
|
@ -535,14 +564,16 @@ impl Editor {
|
|||
let mut cancel = false;
|
||||
egui::Window::new("Open project?").collapsible(false).open(&mut open).show(ctx,|ui| {
|
||||
ui.label(path.display().to_string());
|
||||
ui.label("Opening replaces the current work, undo history and recovery autosave. Cancel and save a separate project first if needed.");
|
||||
ui.label("Opening replaces the current work, undo history and recovery autosave. Embedded parameters restore the original export snapshot, not later artwork edits. Cancel and save a separate project first if needed.");
|
||||
ui.label(self.manual_save_age());
|
||||
ui.horizontal(|ui| {load=ui.button("Open project").clicked();cancel=ui.button("Cancel").clicked();});
|
||||
});
|
||||
if load {
|
||||
self.start_project_job(ctx, false, move || {
|
||||
let project = Project::read(&path)?;
|
||||
Ok(Some((project, Some(path), None)))
|
||||
let (project, native) =
|
||||
midra_layout::interchange::read_project_or_parameters(&path)?;
|
||||
// Never autosave JSON over the source artwork.
|
||||
Ok(Some((project, native.then_some(path), None)))
|
||||
});
|
||||
} else if open && !cancel {
|
||||
self.files.opening = Some(path);
|
||||
|
|
|
|||
|
|
@ -67,6 +67,7 @@ fn craft_dwg_preserves_canvas_background_and_layer_boxes() {
|
|||
&ids,
|
||||
Codec::Dwg,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background,
|
||||
placeholders: false,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -169,6 +169,7 @@ fn every_format_and_artwork_option_roundtrips_geometry_and_order() {
|
|||
&ids,
|
||||
format,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background,
|
||||
placeholders,
|
||||
},
|
||||
|
|
@ -207,6 +208,7 @@ fn every_format_and_artwork_option_roundtrips_geometry_and_order() {
|
|||
&ids,
|
||||
format,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background,
|
||||
placeholders,
|
||||
},
|
||||
|
|
@ -245,6 +247,7 @@ fn single_full_screen_layer_is_never_mistaken_for_background() {
|
|||
&[p.layers[0].id],
|
||||
format,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders,
|
||||
},
|
||||
|
|
@ -266,6 +269,7 @@ fn drawio_compressed_resave_and_percent_encoded_clipboard_are_supported() {
|
|||
&[p.layers[0].id],
|
||||
Format::Drawio,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: true,
|
||||
},
|
||||
|
|
@ -314,6 +318,7 @@ fn reference_image_is_embedded_and_missing_ids_or_invalid_versions_fail() {
|
|||
&[p.layers[0].id],
|
||||
Format::Svg,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: false,
|
||||
},
|
||||
|
|
@ -353,6 +358,7 @@ fn open_text_adapters_reject_wrong_versions_canvases_and_non_rectangles() {
|
|||
&ids,
|
||||
Format::Csv,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: false,
|
||||
placeholders: true,
|
||||
},
|
||||
|
|
@ -436,6 +442,7 @@ fn exported_background_composites_visible_references_in_order() {
|
|||
&[project.layers[0].id],
|
||||
Format::Svg,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: false,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -0,0 +1,265 @@
|
|||
use midra_layout::{
|
||||
Layout,
|
||||
exchange::Options,
|
||||
exchange_metadata as metadata,
|
||||
interchange::{self, Codec},
|
||||
project::Project,
|
||||
};
|
||||
|
||||
fn fixture() -> Project {
|
||||
let mut layout = Layout::default();
|
||||
layout
|
||||
.set_framing(
|
||||
0,
|
||||
midra_layout::formats::Framing {
|
||||
zoom: 1.5,
|
||||
offset: [12.0, -8.0],
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut p = Project::from_layout(&layout);
|
||||
p.layers[0].name = "<Speaker> & \"guest\"".into();
|
||||
p.layers[0].folder = "Memory A".into();
|
||||
p.layers[0].midra_link = Some(midra_layout::MidraLink {
|
||||
screen: "2".into(),
|
||||
layer: "1".into(),
|
||||
});
|
||||
p.workspace.collapsed_folders = vec!["Memory A".into()];
|
||||
p
|
||||
}
|
||||
#[test]
|
||||
fn supported_codecs_preserve_artwork_and_restore_selected_parameters() {
|
||||
let p = fixture();
|
||||
let ids = [p.layers[0].id];
|
||||
let expected = metadata::snapshot(&p, &ids).unwrap();
|
||||
for codec in Codec::available()
|
||||
.into_iter()
|
||||
.filter(|&c| metadata::supported(c))
|
||||
{
|
||||
for background in [false, true] {
|
||||
let plain = interchange::export(
|
||||
&p,
|
||||
&ids,
|
||||
codec,
|
||||
Options {
|
||||
background,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
metadata::extract(&plain, codec).unwrap().is_none(),
|
||||
"{codec:?}"
|
||||
);
|
||||
let bytes = interchange::export(
|
||||
&p,
|
||||
&ids,
|
||||
codec,
|
||||
Options {
|
||||
background,
|
||||
extra_parameters: true,
|
||||
placeholders: codec.artwork(),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
metadata::extract(&bytes, codec).unwrap(),
|
||||
Some(expected.clone()),
|
||||
"{codec:?}"
|
||||
);
|
||||
let filename = format!("layout.{}", codec.extension());
|
||||
let before = interchange::import(&plain, &filename).unwrap();
|
||||
let after = interchange::import(&bytes, &filename).unwrap();
|
||||
let geometries = |pages: Vec<interchange::Page>| {
|
||||
pages
|
||||
.into_iter()
|
||||
.flat_map(|p| {
|
||||
p.document
|
||||
.shapes
|
||||
.into_iter()
|
||||
.filter(|s| !s.background)
|
||||
.map(|s| s.geometry)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(geometries(before), geometries(after), "{codec:?}");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(filename);
|
||||
std::fs::write(&path, &bytes).unwrap();
|
||||
assert_eq!(interchange::read_embedded_project(&path).unwrap(), expected);
|
||||
if let Ok(root) = std::env::var("MIDRA_METADATA_SAMPLES") {
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
std::fs::write(
|
||||
std::path::Path::new(&root).join(format!("sample.{}", codec.extension())),
|
||||
&bytes,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn metadata_is_optional_versioned_and_not_silently_applied_to_edited_artwork() {
|
||||
let p = fixture();
|
||||
let ids = [p.layers[0].id];
|
||||
let bytes = interchange::export(
|
||||
&p,
|
||||
&ids,
|
||||
Codec::Json,
|
||||
Options {
|
||||
extra_parameters: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||
assert_eq!(json["version"], 2);
|
||||
json["layers"][0]["x"] = 777.into();
|
||||
let changed = serde_json::to_vec(&json).unwrap();
|
||||
assert_eq!(
|
||||
interchange::import(&changed, "x.json").unwrap()[0]
|
||||
.document
|
||||
.shapes[0]
|
||||
.geometry
|
||||
.x,
|
||||
777.0
|
||||
);
|
||||
assert_ne!(
|
||||
metadata::extract(&changed, Codec::Json)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.layers[0]
|
||||
.bounds
|
||||
.x,
|
||||
777.0
|
||||
);
|
||||
json[metadata::KEY] = "not base64".into();
|
||||
let invalid = serde_json::to_vec(&json).unwrap();
|
||||
assert!(metadata::extract(&invalid, Codec::Json).is_err());
|
||||
assert!(interchange::import(&invalid, "x.json").is_ok());
|
||||
json.as_object_mut().unwrap().remove(metadata::KEY);
|
||||
assert!(interchange::import(&serde_json::to_vec(&json).unwrap(), "x.json").is_err());
|
||||
for codec in [Codec::Dwg, Codec::Figma, Codec::Illustrator] {
|
||||
assert!(!metadata::supported(codec));
|
||||
assert!(
|
||||
interchange::export(
|
||||
&p,
|
||||
&ids,
|
||||
codec,
|
||||
Options {
|
||||
extra_parameters: true,
|
||||
..Default::default()
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn snapshot_omits_unexported_layers_unused_sources_and_capture_bindings() {
|
||||
let p = fixture();
|
||||
let result = metadata::snapshot(&p, &[p.layers[1].id]).unwrap();
|
||||
assert_eq!(result.layers.len(), 1);
|
||||
assert_eq!(result.inputs.len(), 1);
|
||||
assert_eq!(result.layers[0].source_id, 1);
|
||||
assert!(result.workspace.collapsed_folders.is_empty());
|
||||
assert!(result.references.is_empty() && result.workspace.previews.is_empty());
|
||||
assert!(metadata::snapshot(&p, &[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_drawio_desktop_resave_recovers_embedded_snapshot() {
|
||||
let Ok(root) = std::env::var("MIDRA_METADATA_SAMPLES") else {
|
||||
return;
|
||||
};
|
||||
let path = std::path::Path::new(&root).join("drawio-resaved.svg");
|
||||
if !path.exists() {
|
||||
return;
|
||||
}
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let p = fixture();
|
||||
assert_eq!(
|
||||
metadata::extract(&bytes, Codec::Svg).unwrap(),
|
||||
Some(metadata::snapshot(&p, &[p.layers[0].id]).unwrap())
|
||||
);
|
||||
assert!(interchange::import(&bytes, "resaved.svg").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_parameters_never_reuses_artwork_path_and_keeps_native_errors() {
|
||||
let p = fixture();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("layout.json");
|
||||
std::fs::write(&path, p.to_json().unwrap()).unwrap();
|
||||
assert_eq!(
|
||||
interchange::read_project_or_parameters(&path).unwrap(),
|
||||
(p.clone(), true)
|
||||
);
|
||||
let mut invalid = serde_json::to_value(&p).unwrap();
|
||||
invalid["version"] = 999.into();
|
||||
std::fs::write(&path, invalid.to_string()).unwrap();
|
||||
assert!(
|
||||
interchange::read_project_or_parameters(&path)
|
||||
.unwrap_err()
|
||||
.contains("version")
|
||||
);
|
||||
let bytes = interchange::export(
|
||||
&p,
|
||||
&[p.layers[0].id],
|
||||
Codec::Json,
|
||||
Options {
|
||||
extra_parameters: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
assert!(!interchange::read_project_or_parameters(&path).unwrap().1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn documented_metadata_example_and_pptx_package_relationships_are_valid() {
|
||||
let example =
|
||||
include_bytes!("../../../docs/interfaces/midra-geometry-v2-metadata.example.json");
|
||||
assert_eq!(
|
||||
interchange::import(example, "example.json").unwrap()[0]
|
||||
.document
|
||||
.shapes
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
metadata::extract(example, Codec::Json)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.layout()
|
||||
.unwrap();
|
||||
if !Codec::available().contains(&Codec::Pptx) {
|
||||
return;
|
||||
}
|
||||
use std::io::Read;
|
||||
let p = fixture();
|
||||
let bytes = interchange::export(
|
||||
&p,
|
||||
&[p.layers[0].id],
|
||||
Codec::Pptx,
|
||||
Options {
|
||||
extra_parameters: true,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
|
||||
for name in ["[Content_Types].xml", "_rels/.rels", "docProps/custom.xml"] {
|
||||
let mut text = String::new();
|
||||
zip.by_name(name)
|
||||
.unwrap()
|
||||
.read_to_string(&mut text)
|
||||
.unwrap();
|
||||
let xml = roxmltree::Document::parse(&text).unwrap();
|
||||
match name {
|
||||
"[Content_Types].xml" => assert!(xml.descendants().any(|n| n.attribute("PartName") == Some("/docProps/custom.xml") && n.attribute("ContentType") == Some("application/vnd.openxmlformats-officedocument.custom-properties+xml"))),
|
||||
"_rels/.rels" => assert!(xml.descendants().any(|n| n.attribute("Target") == Some("docProps/custom.xml") && n.attribute("Type") == Some("http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties"))),
|
||||
_ => assert!(xml.descendants().any(|n| n.attribute("name") == Some(metadata::KEY))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -49,6 +49,7 @@ fn native_binary_codecs_roundtrip_boxes_background_and_artwork() {
|
|||
&ids,
|
||||
codec,
|
||||
Options {
|
||||
extra_parameters: false,
|
||||
background: true,
|
||||
placeholders: artwork,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ by regression tests.
|
|||
| [Midra Layout project](midra-layout.md) | JSON project versions, SVG geometry, validation and migration |
|
||||
| [Application settings](midra-layout-settings.md) | Per-user preferences and settings versions |
|
||||
| [Geometry exchange](midra-layout-exchange.md) | Import/export formats, precision, omissions and round trips |
|
||||
| [Extra export parameters](midra-extra-parameters.md) | Optional embedded project snapshots and per-format compatibility |
|
||||
| [Recovery files](midra-layout-recovery.md) | Recovery storage and restore behavior |
|
||||
| [Device import](midra-device-import.md) | Read-only device geometry import |
|
||||
| [Device send](midra-device-send.md) | Reviewed writes, crop conversion and restore diagnostics |
|
||||
|
|
|
|||
|
|
@ -0,0 +1,93 @@
|
|||
# Extra Midra parameters in geometry exports
|
||||
|
||||
This optional extension is selected by **Export layers → Include extra Midra
|
||||
parameters (experimental)**. It defaults off. Plain exports retain their existing
|
||||
representation. Native **Save project** already saves the full project and needs
|
||||
no additional switch.
|
||||
|
||||
Use **Project → Restore parameters from export…** to recover the original snapshot
|
||||
into a new, unsaved project. The existing replacement review applies. The source
|
||||
artwork never becomes the project-save/autosave path. Geometry import and clipboard
|
||||
paste continue to import the artwork's current geometry; they do not silently
|
||||
restore old positions, links or crop settings from metadata. This matters when an
|
||||
external editor moves/resizes a shape without updating the embedded snapshot.
|
||||
|
||||
## Format audit and implemented carriers
|
||||
|
||||
| Format | Carrier / result | Compatibility limits |
|
||||
| --- | --- | --- |
|
||||
| SVG | `<metadata><parameters xmlns="urn:beffroi:midra:parameters:1">BASE64</parameters></metadata>` inside the SVG root | Non-rendered foreign-namespace metadata. SVG geometry exchange remains v2. Tested with librsvg rendering. Optimizers may remove metadata. |
|
||||
| draw.io | Global root-cell custom property: `<object id="0" beffroi_midra_parameters="BASE64"><mxCell/></object>` | Graph model/geometry version stays 1. Installed draw.io Desktop opened and exported this to SVG; parameters also recovered from the SVG's embedded diagram. Compressed single-page draw.io models are supported through the existing bounded decoder. |
|
||||
| Geometry JSON | Version **2**, required root string `beffroi_midra_parameters` | All v1 geometry fields unchanged. Versions 1 and 2 import; v1 exporters remain byte-compatible when the option is off. Older strict readers reject v2 rather than misread it. |
|
||||
| Geometry CSV | Version **2** in every row; added `beffroi_midra_parameters` column | The first data row holds BASE64; remaining rows contain empty cells. Header/row widths remain equal and ordinary CSV quoting is used. No nonstandard comment lines. Versions 1 and 2 import; older schema-aware readers reject v2. |
|
||||
| ASCII DXF | Group **999** comments after the existing geometry marker, each `beffroi-midra-parameters:CHUNK` | Ordered base64 chunks of at most 200 characters (comment lines under 255). Craft still reads the same rectangles. Comments may be stripped on CAD resave; binary DXF does not use group 999. |
|
||||
| HTML | `<meta name="beffroi_midra_parameters" content="BASE64"/>` in `<head>` | Inert document metadata, no scripts or hidden visible objects. HTML geometry version stays 1. |
|
||||
| PPTX | `docProps/custom.xml`, string property `beffroi_midra_parameters` | Standard custom-properties content type and package-root relationship; `vt:lpwstr`, pid 2, fmtid `{D5CDD505-2E9C-101B-9397-08002B2CF9AE}`. Existing ZIP parts are preserved; native DeckCraft import checks unchanged geometry. Microsoft PowerPoint resave not tested here. |
|
||||
| DWG | Not enabled | DXF comments do not provide a reliable binary-DWG carrier. XRECORD/XData are potential future paths, but the current Craft conversion bridge has no verified application-payload round trip. No bytes are appended to the binary file. |
|
||||
| Figma FIG | Not enabled | Figma has plugin data, but the installed FigCraft 0.5.1 native exporter explicitly warns `plugin data was left out`. Its model field is not evidence of native preservation. |
|
||||
| Illustrator AI | Not enabled | PDF-compatible AI can have document metadata, but the current VectorCraft SVG↔AI conversion path has no verified application-payload preservation. No unverified PDF/AI trailer changes are made. |
|
||||
| Midra project JSON | Already complete | Project v11 remains the authoritative full-fidelity save. This task does not change its schema. |
|
||||
|
||||
Unsupported codecs disable the option with an explanation. Programmatic attempts
|
||||
to request the extension on those codecs fail explicitly, never silently discard
|
||||
it. Vendor availability and the `no_proprietary` build flag still apply.
|
||||
|
||||
## Payload contract (extension version 1)
|
||||
|
||||
`BASE64` is standard padded RFC 4648 base64 of UTF-8, pretty-printed
|
||||
[project JSON](midra-layout.md), currently version 11. It is inert data, not an
|
||||
executable instruction, URL or file path. Project format/version and validation
|
||||
remain authoritative. Future incompatible carrier/payload meanings require a new
|
||||
extension version and explicit migration or rejection.
|
||||
|
||||
The snapshot includes only exported layer IDs, in document stack order, with
|
||||
full-precision bounds, names, folders, visibility, locks, pivots, Midra links,
|
||||
source/input crop and advanced crop. Only referenced input slots are included;
|
||||
source IDs are remapped consecutively, preserving shared source relationships.
|
||||
Selection and collapsed folders are filtered to retained layers. Output resolution,
|
||||
positioning, camera, guide and workspace settings remain available. Pixel-rounded
|
||||
artwork and full-precision stored coordinates are intentionally distinct.
|
||||
|
||||
All reference-image objects and preview assignments/images/device-address bindings
|
||||
are omitted. Artwork background/placeholder options operate independently; they do
|
||||
not embed capture settings. Application preferences, connection history, active
|
||||
connections, pending device edits/jobs and undo history are never included.
|
||||
|
||||
The decoded metadata JSON is limited to **1 MiB**, and the complete exchange file
|
||||
still must fit within **16 MiB** after embedding. PPTX custom-properties XML reads
|
||||
are bounded to 2 MiB. No archive members are extracted onto the filesystem. Invalid
|
||||
base64 or project data rejects explicit snapshot restoration. For geometry JSON
|
||||
and CSV, the known v2 extension is removed before strict v1 geometry validation;
|
||||
invalid optional payload contents do not prevent importing otherwise valid artwork.
|
||||
Unknown versions and unknown geometry fields remain errors. More than one nonempty
|
||||
CSV snapshot is rejected on restoration.
|
||||
|
||||
The [JSON v2 example](midra-geometry-v2-metadata.example.json) is a tested example;
|
||||
its decoded snapshot is also validated as a project. Plain v1 fixtures remain
|
||||
unchanged. Other carriers use the same payload bytes and are round-trip tested
|
||||
with background on/off and optional placeholders. The regression suite also checks
|
||||
that edited artwork is imported as edited, unsupported codecs refuse the option,
|
||||
and recovered exports are never reused as project-save paths.
|
||||
|
||||
## Standards and codec evidence
|
||||
|
||||
- [W3C SVG extensibility](https://www.w3.org/TR/SVG11/extend.html) explicitly allows
|
||||
application metadata for round trips; [SVG 2 structure](https://www.w3.org/TR/SVG2/struct.html)
|
||||
describes metadata containers.
|
||||
- [draw.io global custom properties](https://www.drawio.com/docs/manual/advanced/global-custom-properties/)
|
||||
documents root-cell custom data.
|
||||
- [Autodesk DXF group codes](https://help.autodesk.com/cloudhelp/2024/ENU/AutoCAD-DXF/files/GUID-3F0380A5-1C15-464D-BC66-2C5F094BCFB9.htm)
|
||||
documents group 999 comments. [Binary DXF](https://help.autodesk.com/cloudhelp/2023/ENU/AutoCAD-DXF/files/GUID-FC1C3C69-DBC2-49E4-893A-000D6538C0FE.htm)
|
||||
does not use that comment group.
|
||||
- [WHATWG document metadata](https://html.spec.whatwg.org/dev/semantics.html)
|
||||
describes name/content metadata. [RFC 4180](https://www.rfc-editor.org/rfc/rfc4180)
|
||||
describes CSV fields and quoting; this extension adds a regular column.
|
||||
- [Microsoft custom properties](https://learn.microsoft.com/en-us/office/open-xml/word/how-to-set-a-custom-property-in-a-word-processing-document)
|
||||
describes the shared Open XML custom-property representation; its package
|
||||
relationship applies to presentations too.
|
||||
- [Figma plugin data](https://developers.figma.com/docs/rest-api/file-endpoints/)
|
||||
exists in the platform. The local `figcraft-format 0.5.1/src/fig/export.rs`
|
||||
exporter nevertheless rejects preservation in `plugin_data`; support stays off.
|
||||
- Craft DWG source inspected at revision
|
||||
`79e97b6febcb62de406e5bcf5a724bd3f7333065`; current native adapter conversion
|
||||
boundaries are in `crates/midra-layout/src/vendor_formats.rs`.
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"format": "beffroi.midra-geometry",
|
||||
"version": 2,
|
||||
"units": "px",
|
||||
"canvas": {
|
||||
"width": 1920,
|
||||
"height": 1080
|
||||
},
|
||||
"layers": [
|
||||
{
|
||||
"id": "2",
|
||||
"name": "Slides",
|
||||
"role": "layer",
|
||||
"x": 120,
|
||||
"y": 180,
|
||||
"width": 640,
|
||||
"height": 360
|
||||
},
|
||||
{
|
||||
"id": "1",
|
||||
"name": "Presenter",
|
||||
"role": "layer",
|
||||
"x": 1160,
|
||||
"y": 180,
|
||||
"width": 640,
|
||||
"height": 360
|
||||
}
|
||||
],
|
||||
"beffroi_midra_parameters": "ewogICJmb3JtYXQiOiAiYmVmZnJvaS5taWRyYS1sYXlvdXQiLAogICJ2ZXJzaW9uIjogMTEsCiAgIm91dHB1dF9yZXNvbHV0aW9uIjogewogICAgIndpZHRoIjogMTkyMCwKICAgICJoZWlnaHQiOiAxMDgwCiAgfSwKICAiaW5wdXRzIjogWwogICAgewogICAgICAiaWQiOiAxLAogICAgICAic291cmNlX2Zvcm1hdCI6ICJzaXh0ZWVuX25pbmUiLAogICAgICAibmF0aXZlX3Jlc29sdXRpb24iOiB7CiAgICAgICAgIndpZHRoIjogMTkyMCwKICAgICAgICAiaGVpZ2h0IjogMTA4MAogICAgICB9LAogICAgICAiaW5wdXRfY3JvcCI6IHsKICAgICAgICAibGVmdCI6IDAuMCwKICAgICAgICAicmlnaHQiOiAwLjAsCiAgICAgICAgInRvcCI6IDAuMCwKICAgICAgICAiYm90dG9tIjogMC4wCiAgICAgIH0KICAgIH0sCiAgICB7CiAgICAgICJpZCI6IDIsCiAgICAgICJzb3VyY2VfZm9ybWF0IjogInNpeHRlZW5fbmluZSIsCiAgICAgICJuYXRpdmVfcmVzb2x1dGlvbiI6IHsKICAgICAgICAid2lkdGgiOiAxOTIwLAogICAgICAgICJoZWlnaHQiOiAxMDgwCiAgICAgIH0sCiAgICAgICJpbnB1dF9jcm9wIjogewogICAgICAgICJsZWZ0IjogMC4wLAogICAgICAgICJyaWdodCI6IDAuMCwKICAgICAgICAidG9wIjogMC4wLAogICAgICAgICJib3R0b20iOiAwLjAKICAgICAgfQogICAgfQogIF0sCiAgImxheWVycyI6IFsKICAgIHsKICAgICAgImlkIjogMiwKICAgICAgInNvdXJjZV9pZCI6IDEsCiAgICAgICJib3VuZHMiOiB7CiAgICAgICAgIngiOiAxMjAuMCwKICAgICAgICAieSI6IDE4MC4wLAogICAgICAgICJ3aWR0aCI6IDY0MC4wLAogICAgICAgICJoZWlnaHQiOiAzNjAuMAogICAgICB9LAogICAgICAiYWR2YW5jZWRfY3JvcCI6IHsKICAgICAgICAibGVmdCI6IDAuMCwKICAgICAgICAicmlnaHQiOiAwLjAsCiAgICAgICAgInRvcCI6IDAuMCwKICAgICAgICAiYm90dG9tIjogMC4wCiAgICAgIH0sCiAgICAgICJ2aXNpYmxlIjogdHJ1ZSwKICAgICAgImxvY2tlZCI6IGZhbHNlLAogICAgICAibmFtZSI6ICJTbGlkZXMiLAogICAgICAiZm9sZGVyIjogIiIsCiAgICAgICJtaWRyYV9saW5rIjogbnVsbCwKICAgICAgInBpdm90IjogWwogICAgICAgIDAuNSwKICAgICAgICAwLjUKICAgICAgXQogICAgfSwKICAgIHsKICAgICAgImlkIjogMSwKICAgICAgInNvdXJjZV9pZCI6IDIsCiAgICAgICJib3VuZHMiOiB7CiAgICAgICAgIngiOiAxMTYwLjAsCiAgICAgICAgInkiOiAxODAuMCwKICAgICAgICAid2lkdGgiOiA2NDAuMCwKICAgICAgICAiaGVpZ2h0IjogMzYwLjAKICAgICAgfSwKICAgICAgImFkdmFuY2VkX2Nyb3AiOiB7CiAgICAgICAgImxlZnQiOiAwLjAsCiAgICAgICAgInJpZ2h0IjogMC4wLAogICAgICAgICJ0b3AiOiAwLjAsCiAgICAgICAgImJvdHRvbSI6IDAuMAogICAgICB9LAogICAgICAidmlzaWJsZSI6IHRydWUsCiAgICAgICJsb2NrZWQiOiBmYWxzZSwKICAgICAgIm5hbWUiOiAiUHJlc2VudGVyIiwKICAgICAgImZvbGRlciI6ICIiLAogICAgICAibWlkcmFfbGluayI6IG51bGwsCiAgICAgICJwaXZvdCI6IFsKICAgICAgICAwLjUsCiAgICAgICAgMC41CiAgICAgIF0KICAgIH0KICBdLAogICJlZGl0b3IiOiB7CiAgICAiYmFja2Ryb3BfdGl0bGUiOiAiRXhhbXBsZSBDb25mZXJlbmNlIE5hbWUiLAogICAgInNlbGVjdGVkX2xheWVyX2lkcyI6IFsKICAgICAgMQogICAgXSwKICAgICJwb3NpdGlvbl9wb2ludCI6ICJ0b3BfbGVmdCIsCiAgICAia2VlcF9hc3BlY3RfcmF0aW8iOiB0cnVlLAogICAgInZpZXdwb3J0X3pvb20iOiAxLjAsCiAgICAidmlld3BvcnRfcGFuIjogWwogICAgICAwLjAsCiAgICAgIDAuMAogICAgXSwKICAgICJzaG93X3NvdXJjZV9wYXR0ZXJuIjogZmFsc2UsCiAgICAic2hvd190b29sYmFyX2ljb25fbmFtZXMiOiBmYWxzZSwKICAgICJvdXRsaW5lX2xheWVycyI6IGZhbHNlLAogICAgInBvc2l0aW9uX2xheWVyX3BvaW50IjogbnVsbAogIH0sCiAgIm5leHRfbGF5ZXJfaWQiOiAzLAogICJyZWZlcmVuY2VzIjogW10sCiAgIndvcmtzcGFjZSI6IHsKICAgICJzbmFwcGluZyI6IHsKICAgICAgImVuYWJsZWQiOiBmYWxzZSwKICAgICAgInBpeGVscyI6IHRydWUsCiAgICAgICJzY3JlZW5fZWRnZXMiOiB0cnVlLAogICAgICAibGF5ZXJfZWRnZXMiOiB0cnVlLAogICAgICAiZ3JpZCI6IGZhbHNlLAogICAgICAic2hvd19ncmlkIjogdHJ1ZSwKICAgICAgImdyaWRfZGl2aXNpb25zIjogWwogICAgICAgIDgsCiAgICAgICAgNgogICAgICBdCiAgICB9LAogICAgInJlc2l6ZV9tb2RlIjogImluZGl2aWR1YWwiLAogICAgImdyaWRfc3BhY2luZyI6IG51bGwsCiAgICAiY29sbGFwc2VkX2ZvbGRlcnMiOiBbXSwKICAgICJjYXB0dXJlX2ludGVydmFsX3NlY29uZHMiOiAxMCwKICAgICJzaG93X2VtcHR5X2lucHV0cyI6IGZhbHNlLAogICAgInByZXZpZXdzIjogW10KICB9Cn0K"
|
||||
}
|
||||
|
|
@ -398,3 +398,18 @@ cargo run --locked -p midra-layout --example check_geometry_exchange -- verify /
|
|||
The verifier now uses the unified byte importer for text and binary formats.
|
||||
The `.ai` starter ZIP is only a download wrapper, not a new import format; its
|
||||
two entries must remain byte-identical to the `.ai` fixtures (Python regression).
|
||||
|
||||
## Optional extra Midra parameters
|
||||
|
||||
Export layers offers **Include extra Midra parameters (experimental)** for SVG,
|
||||
draw.io, JSON, CSV, DXF, HTML and PPTX. This embeds an inert snapshot separately
|
||||
from the artwork. JSON/CSV use geometry version 2 only when enabled; plain exports
|
||||
remain version 1. Other carrier versions remain unchanged. Existing omissions in
|
||||
this document describe plain geometry export; the optional snapshot preserves
|
||||
source/crop, identity, links and workspace settings, excluding image bytes and
|
||||
capture bindings. See the [complete carrier contract and format audit](midra-extra-parameters.md).
|
||||
|
||||
Restore the original snapshot with **Project → Restore parameters from export…**.
|
||||
Normal geometry import continues to use the artwork's current boxes, including any
|
||||
external edits. Third-party editors may strip metadata. DWG, FIG and AI are not
|
||||
enabled until their current codec paths can preserve it reliably.
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
- [Project file contract](../../interfaces/midra-layout.md)
|
||||
- [Persistence audit](../../interfaces/midra-layout-persistence-audit.md)
|
||||
- [Geometry exchange contract](../../interfaces/midra-layout-exchange.md)
|
||||
- [Extra export parameters](../../interfaces/midra-extra-parameters.md)
|
||||
- [Settings contract](../../interfaces/midra-layout-settings.md)
|
||||
- [Recovery contract](../../interfaces/midra-layout-recovery.md)
|
||||
- [Device import contract](../../interfaces/midra-device-import.md)
|
||||
|
|
|
|||
|
|
@ -4,6 +4,15 @@
|
|||
|
||||
## Unreleased
|
||||
|
||||
- Add opt-in extra Midra parameters to SVG, draw.io, geometry JSON/CSV, ASCII DXF,
|
||||
HTML and PPTX, using metadata/custom fields or comments. Geometry remains
|
||||
editable; explicit Restore parameters from export recovers the original snapshot
|
||||
into an unsaved project. JSON/CSV v2 carries metadata; plain v1 exports are
|
||||
unchanged. Document all formats, including disabled DWG/FIG/AI codec limitations.
|
||||
Round-trip tests cover settings and geometry; installed draw.io exported the
|
||||
metadata-bearing diagram to SVG, and librsvg rendered both SVG variants.
|
||||
|
||||
|
||||
- Audit project persistence: version 11 now saves snapping/grid setup, group resize
|
||||
mode, collapsed folders, capture assignments/stills, guide opacity and refresh
|
||||
settings. Saved auto-refresh reopens paused. Versions 1–10 migrate explicitly;
|
||||
|
|
|
|||
|
|
@ -295,3 +295,22 @@ gestures and pending device operations are temporary. Transfer scope, target ban
|
|||
sizing strategy and opt-in advanced device input edits remain session choices.
|
||||
See the [complete persistence audit](../../interfaces/midra-layout-persistence-audit.md)
|
||||
and [versioned project contract](../../interfaces/midra-layout.md).
|
||||
|
||||
## Extra settings inside artwork exports
|
||||
|
||||
In **Export layers**, enable **Include extra Midra parameters (experimental)** to
|
||||
store the exported layers' source/crop settings, names, folders, links and workspace
|
||||
setup alongside the geometry. It is available for SVG, draw.io, JSON, CSV, DXF,
|
||||
HTML and PPTX. Images/capture assignments are excluded from this snapshot; the
|
||||
background and placeholder options remain separate. DWG, FIG and AI show why the
|
||||
option is unavailable with the current codecs.
|
||||
|
||||
Use **Project → Restore parameters from export…** to restore that original
|
||||
snapshot as an unsaved project. This replaces the current editor document after
|
||||
review, and never overwrites the artwork with a project file. To import changes
|
||||
made in another program, continue to use **Import → Geometry file…**: the embedded
|
||||
snapshot can be older than the artwork, so it is never applied automatically.
|
||||
Other programs may remove the extra data when resaving. **Save project** remains
|
||||
the complete save, including reference images and captured previews.
|
||||
|
||||
See the [format-by-format audit and metadata contract](../../interfaces/midra-extra-parameters.md).
|
||||
|
|
|
|||
Loading…
Reference in New Issue