beffroi-tools/crates/midra-layout/src/exchange.rs

245 lines
8.7 KiB
Rust

//! 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('&', "&")
.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"));
}
}
}