Add versioned Midra project save/load and SVG geometry export

This commit is contained in:
Dandaedre 2026-11-13 15:03:10 +01:00
parent dc5c4f14fe
commit e6ebc114b2
15 changed files with 1001 additions and 6 deletions

View File

@ -99,6 +99,19 @@ with quick-start examples and links to detailed documentation in `docs/`.
Run `python3 scripts/ci.py coverage` for the whole Rust application; do not
exclude production GUI/PDF code to raise the reported percentage.
## Save/export interfaces
- Document every persistent save and export format under `docs/interfaces/`,
including field names, units, precision, versioning, validation, omissions,
import/round-trip behavior, and compatibility expectations.
- Whenever a save-file schema or export representation changes, update the
corresponding interface documentation, examples, and regression tests in the
same task. Do not leave `interfaces` out of a schema change.
- Version breaking changes explicitly; provide a tested migration or a clear
unsupported-version error rather than silently interpreting incompatible data.
- Midra Layout's JSON project and SVG geometry contracts are in
`docs/interfaces/midra-layout.md`.
## Commit every task
- Every completed task that changes repository files must end with a Git commit.

4
Cargo.lock generated
View File

@ -2395,11 +2395,15 @@ dependencies = [
name = "midra-layout"
version = "0.3.0"
dependencies = [
"base64 0.22.1",
"eframe",
"image",
"rfd",
"roxmltree",
"serde",
"serde_json",
"svgtypes",
"tempfile",
]
[[package]]

View File

@ -47,7 +47,7 @@ opening reports, and reading video timings.
- [ASCII filename cleaner](docs/ascii-names.md)
- [Document exports](docs/exporter.md)
- [Rundown converter](docs/rundown-converter.md) · [Sample findings](docs/rundown-corpus.md)
- [Midra layout helper](docs/midra-layout.md) · [Plan and visual proposals](docs/midra-layout-plan.md)
- [Midra layout helper](docs/midra-layout.md) · [Plan and visual proposals](docs/midra-layout-plan.md) · [File formats](docs/interfaces/midra-layout.md)
- [Development](docs/development.md) · [CI and coverage](docs/ci.md)
- [Cross builds and portable releases](docs/releases.md)
- [MPC-HC Companion module development](companion-modules/media-player-classic/README.md)

View File

@ -12,3 +12,7 @@ eframe = { version = "0.31", default-features = false, features = ["default_font
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp"] }
rfd = "0.15"
svgtypes = "0.15"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["float_roundtrip"] }
base64 = "0.22"
tempfile = "3"

View File

@ -1,7 +1,8 @@
//! Source-space cropping and output-space framing. No device protocol assumptions.
use crate::Geometry;
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Aspect {
FourThree,
SixteenNine,
@ -36,7 +37,8 @@ impl Aspect {
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Crop {
pub left: f64,
pub right: f64,

View File

@ -1,12 +1,15 @@
use super::*;
#[path = "format_ui.rs"]
mod format_ui;
#[path = "project_ui.rs"]
mod project_ui;
use format_ui::{FormatDraft, OutputDraft, PropertyTab};
use midra_layout::import::{DetectedShape, ImportDocument, parse_svg, parse_values};
use midra_layout::{AlignTarget, Alignment, Corner, Geometry, Layout, ResizeHandle, ResizeMode};
pub struct Editor {
layout: Layout,
files: project_ui::FileUi,
corner: Corner,
fields: [String; 4],
error: String,
@ -161,6 +164,7 @@ impl Default for Editor {
fn default() -> Self {
let mut this = Self {
layout: Layout::default(),
files: project_ui::FileUi::default(),
corner: Corner::TopRight,
fields: Default::default(),
error: String::new(),
@ -1418,6 +1422,18 @@ impl Editor {
));
},
);
ui.scope_builder(
egui::UiBuilder::new()
.max_rect(Rect::from_min_size(
ink.point(362.0, 21.0),
Vec2::new(100.0, 34.0),
))
.layout(egui::Layout::left_to_right(egui::Align::Center)),
|ui| {
ui.spacing_mut().interact_size.y = 34.0;
ui.menu_button("Project", |ui| self.project_menu(ui));
},
);
ui.put(
Rect::from_min_size(ink.point(24.0, 63.0), Vec2::new(310.0, 20.0)),
egui::Checkbox::new(
@ -1995,6 +2011,7 @@ impl Editor {
self.reference_window(ctx);
self.output_window(ctx);
self.formats_window(ctx);
self.project_windows(ctx);
}
}

View File

@ -419,7 +419,13 @@ fn walk(
&& geometry.y.abs() < 1e-6
&& (geometry.width - page[0]).abs() < 1e-6
&& (geometry.height - page[1]).abs() < 1e-6;
let background = out.is_empty() && full_page;
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());
}

View File

@ -2,6 +2,7 @@
use std::collections::HashMap;
pub mod formats;
pub mod import;
pub mod project;
use formats::{Formats, Framing, Source};
/// Presentation only: retain full precision in the document.
@ -171,7 +172,8 @@ fn anchored_resize(original: Geometry, handle: ResizeHandle, width: f64, height:
}
/// Visible layer bounds, in output screen pixels. No crop or camera transform.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Geometry {
pub x: f64,
pub y: f64,
@ -210,7 +212,8 @@ impl Geometry {
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Corner {
#[default]
TopLeft,

View File

@ -0,0 +1,254 @@
//! Versioned offline interchange. Contract: docs/interfaces/midra-layout.md.
use crate::{
Corner, Geometry, Layout,
formats::{self, Aspect, Crop, Source},
};
use base64::{Engine, engine::general_purpose::STANDARD};
use serde::{Deserialize, Serialize};
use std::{
io::{Read, Write},
path::Path,
};
pub const MAX_PROJECT_BYTES: u64 = 96 * 1024 * 1024;
pub const FORMAT: &str = "beffroi.midra-layout";
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Resolution {
pub width: u32,
pub height: u32,
}
impl From<[u32; 2]> for Resolution {
fn from([width, height]: [u32; 2]) -> Self {
Self { width, height }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Input {
pub id: usize,
pub source_format: Aspect,
pub native_resolution: Resolution,
pub input_crop: Crop,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Layer {
pub id: usize,
pub source_id: usize,
pub bounds: Geometry,
pub advanced_crop: Crop,
pub visible: bool,
pub locked: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Reference {
pub name: String,
pub image_base64: String,
pub visible: bool,
pub opacity: f32,
pub preserve_ratio: bool,
}
impl Reference {
pub fn bytes(&self) -> Result<Vec<u8>, String> {
if !self.opacity.is_finite() || !(0.0..=1.0).contains(&self.opacity) {
return Err("Reference opacity must be between 0 and 1.".into());
}
if self.image_base64.len() > 90 * 1024 * 1024 {
return Err("Reference image is too large.".into());
}
let bytes = STANDARD
.decode(&self.image_base64)
.map_err(|e| format!("Invalid embedded reference: {e}"))?;
if bytes.len() > 64 * 1024 * 1024 {
return Err("Reference image exceeds 64 MiB.".into());
}
Ok(bytes)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EditorSettings {
pub selected_layer_ids: Vec<usize>,
pub position_corner: Corner,
pub keep_aspect_ratio: bool,
pub viewport_zoom: f32,
pub viewport_pan: [f32; 2],
pub show_source_pattern: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Project {
pub format: String,
pub version: u32,
pub output_resolution: Resolution,
pub inputs: [Input; 2],
pub layers: [Layer; 2],
pub reference: Option<Reference>,
pub editor: EditorSettings,
}
impl Project {
pub fn from_layout(layout: &Layout) -> Self {
Self {
format: FORMAT.into(),
version: 1,
output_resolution: layout.formats.output.into(),
inputs: std::array::from_fn(|i| {
let source = layout.formats.sources[i];
Input {
id: i + 1,
source_format: source.aspect,
native_resolution: source.native.into(),
input_crop: source.input_crop,
}
}),
layers: std::array::from_fn(|i| Layer {
id: i + 1,
source_id: layout.formats.source_for[i] + 1,
bounds: layout.layers[i],
advanced_crop: layout.formats.advanced[i],
visible: layout.visible[i],
locked: layout.locked[i],
}),
reference: None,
editor: EditorSettings {
selected_layer_ids: layout
.selected_indices()
.into_iter()
.map(|i| i + 1)
.collect(),
position_corner: Corner::TopLeft,
keep_aspect_ratio: true,
viewport_zoom: 1.0,
viewport_pan: [0.0; 2],
show_source_pattern: false,
},
}
}
/// Build a fresh document only after validating the entire file. No history is restored.
pub fn layout(&self) -> Result<Layout, String> {
if self.format != FORMAT || self.version != 1 {
return Err(
"Unsupported project format/version; expected beffroi.midra-layout version 1."
.into(),
);
}
let output = [self.output_resolution.width, self.output_resolution.height];
formats::validate_resolution(output)?;
let mut layout = Layout::default();
layout.formats.output = output;
for (i, input) in self.inputs.iter().enumerate() {
if input.id != i + 1 {
return Err("Input IDs must be 1, 2 in order.".into());
}
let source = Source {
aspect: input.source_format,
native: [
input.native_resolution.width,
input.native_resolution.height,
],
input_crop: input.input_crop,
};
source.input()?;
layout.formats.sources[i] = source;
}
for (i, layer) in self.layers.iter().enumerate() {
if layer.id != i + 1 || !(1..=2).contains(&layer.source_id) {
return Err("Layer IDs must be 1, 2 in order; source IDs must be 1 or 2.".into());
}
layer.bounds.validate()?;
layout.layers[i] = layer.bounds;
layout.formats.source_for[i] = layer.source_id - 1;
layout.formats.advanced[i] = layer.advanced_crop;
layout.formats.mapping(i, layer.bounds)?;
layout.visible[i] = layer.visible;
layout.locked[i] = layer.locked;
}
let e = &self.editor;
if !e.viewport_zoom.is_finite()
|| !(0.0001..=256.0).contains(&e.viewport_zoom)
|| e.viewport_pan
.iter()
.any(|v| !v.is_finite() || v.abs() > 1e9)
{
return Err("Invalid viewport camera settings.".into());
}
layout.selected = [false; 2];
for &id in &e.selected_layer_ids {
if !(1..=2).contains(&id) || layout.selected[id - 1] || !layout.selectable(id - 1) {
return Err("Selected layer IDs must be unique, visible, unlocked layers.".into());
}
layout.selected[id - 1] = true;
}
if let Some(r) = &self.reference {
r.bytes()?;
}
Ok(layout)
}
pub fn to_json(&self) -> Result<String, String> {
self.layout()?;
serde_json::to_string_pretty(self)
.map(|s| s + "\n")
.map_err(|e| e.to_string())
}
pub fn from_json(text: &str) -> Result<Self, String> {
if text.len() as u64 > MAX_PROJECT_BYTES {
return Err("Project exceeds 96 MiB.".into());
}
let p: Self =
serde_json::from_str(text).map_err(|e| format!("Invalid project JSON: {e}"))?;
p.layout()?;
Ok(p)
}
pub fn read(path: &Path) -> Result<Self, String> {
let mut text = String::new();
std::fs::File::open(path)
.map_err(|e| e.to_string())?
.take(MAX_PROJECT_BYTES + 1)
.read_to_string(&mut text)
.map_err(|e| e.to_string())?;
Self::from_json(&text)
}
/// Geometry exchange only: pixel-rounded rectangles, no device commands or hidden metadata.
pub fn to_svg(&self, visible_only: bool) -> Result<String, String> {
self.layout()?;
if visible_only && self.layers.iter().all(|l| !l.visible) {
return Err("No visible layers to export.".into());
}
let w = self.output_resolution.width;
let h = self.output_resolution.height;
let mut svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" data-midra-layout-geometry=\"1\" width=\"{w}\" height=\"{h}\" viewBox=\"0 0 {w} {h}\">\n<title>Midra Layout geometry</title>\n"
);
for layer in &self.layers {
if visible_only && !layer.visible {
continue;
}
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 SVG export.".into());
}
svg.push_str(&format!("<rect id=\"layer-{}\" x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"#173b50\"/>\n",layer.id,crate::export_pixels(g.x),crate::export_pixels(g.y),crate::export_pixels(g.width),crate::export_pixels(g.height)));
}
svg.push_str("</svg>\n");
Ok(svg)
}
}
/// Same-directory temporary write and atomic publication. Existing files require explicit consent.
pub fn write_file(path: &Path, contents: &[u8], overwrite: bool) -> Result<(), String> {
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let mut file = tempfile::NamedTempFile::new_in(parent).map_err(|e| e.to_string())?;
file.write_all(contents)
.and_then(|_| file.as_file().sync_all())
.map_err(|e| e.to_string())?;
if overwrite {
file.persist(path).map_err(|e| e.to_string())?;
} else {
file.persist_noclobber(path).map_err(|e| e.to_string())?;
}
Ok(())
}

View File

@ -0,0 +1,282 @@
use super::*;
use base64::{Engine, engine::general_purpose::STANDARD};
use midra_layout::project::{Project, Reference as SavedReference, write_file};
use std::path::PathBuf;
#[derive(Default)]
pub(super) struct FileUi {
opening: Option<(PathBuf, Project)>,
writing: Option<(PathBuf, String)>,
message: Option<String>,
}
impl Editor {
fn project(&self) -> Project {
let mut p = Project::from_layout(&self.layout);
p.editor.position_corner = self.corner;
p.editor.keep_aspect_ratio = self.keep_aspect_ratio;
p.editor.viewport_zoom = self.zoom;
p.editor.viewport_pan = [self.pan.x, self.pan.y];
p.editor.show_source_pattern = self.show_pattern;
p.reference = self.reference.as_ref().map(|r| SavedReference {
name: r.name.clone(),
image_base64: STANDARD.encode(&r.bytes),
visible: r.visible,
opacity: r.opacity,
preserve_ratio: r.preserve_ratio,
});
p
}
fn install_project(&mut self, ctx: &egui::Context, project: Project) -> Result<(), String> {
let layout = project.layout()?;
let reference = project
.reference
.as_ref()
.map(|r| {
let file = egui::DroppedFile {
name: r.name.clone(),
bytes: Some(r.bytes()?.into()),
..Default::default()
};
let mut reference = super::super::reference::Reference::load(ctx, &file)?;
reference.visible = r.visible;
reference.opacity = r.opacity;
reference.preserve_ratio = r.preserve_ratio;
Ok::<_, String>(reference)
})
.transpose()?;
let e = project.editor;
// Replace only after both the document and embedded image are ready.
*self = Self {
layout,
reference,
corner: e.position_corner,
keep_aspect_ratio: e.keep_aspect_ratio,
zoom: e.viewport_zoom,
pan: Vec2::from(e.viewport_pan),
show_pattern: e.show_source_pattern,
..Default::default()
};
self.sync();
Ok(())
}
fn save_project_as(&mut self) {
self.layout.finish_drag();
match self.project().to_json() {
Ok(contents) => {
if let Some(path) = rfd::FileDialog::new()
.add_filter("Midra Layout project", &["json"])
.set_file_name("layout.midra.json")
.save_file()
{
self.queue_write(path, contents);
}
}
Err(e) => self.files.message = Some(e),
}
}
fn queue_write(&mut self, path: PathBuf, contents: String) {
if path.try_exists().unwrap_or(true) {
self.files.writing = Some((path, contents));
} else {
self.write_project_file(path, contents, false);
}
}
fn write_project_file(&mut self, path: PathBuf, contents: String, overwrite: bool) {
self.files.message = Some(match write_file(&path, contents.as_bytes(), overwrite) {
Ok(()) => format!("Saved {}", path.display()),
Err(e) => format!("Could not save {}: {e}", path.display()),
});
}
pub(super) fn project_menu(&mut self, ui: &mut egui::Ui) {
if ui.button("Open project…").clicked() {
ui.close_menu();
if let Some(path) = rfd::FileDialog::new()
.add_filter("Midra Layout project", &["json"])
.pick_file()
{
match Project::read(&path) {
Ok(p) => self.files.opening = Some((path, p)),
Err(e) => self.files.message = Some(format!("Cannot open project: {e}")),
}
}
}
if ui.button("Save project…").clicked() {
ui.close_menu();
self.save_project_as();
}
ui.small("Saves applied values and the reference image.");
ui.separator();
ui.menu_button("Export SVG", |ui| {
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.");
});
}
pub(super) fn project_windows(&mut self, ctx: &egui::Context) {
if let Some((path, project)) = self.files.opening.take() {
let mut open = true;
let mut load = false;
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 and undo history. Cancel and save the current project first if needed.");
ui.horizontal(|ui| {load=ui.button("Open project").clicked();cancel=ui.button("Cancel").clicked();});
});
if load {
self.files.message = Some(match self.install_project(ctx, project) {
Ok(()) => format!("Opened {}", path.display()),
Err(e) => format!("Cannot open project; current work kept: {e}"),
});
} else if open && !cancel {
self.files.opening = Some((path, project));
}
}
if let Some((path, contents)) = self.files.writing.take() {
let mut open = true;
let mut replace = false;
let mut cancel = false;
egui::Window::new("Replace existing file?")
.collapsible(false)
.open(&mut open)
.show(ctx, |ui| {
ui.label(path.display().to_string());
ui.horizontal(|ui| {
replace = ui.button("Replace file").clicked();
cancel = ui.button("Cancel").clicked();
});
});
if replace {
self.write_project_file(path, contents, true);
} else if open && !cancel {
self.files.writing = Some((path, contents));
}
}
if let Some(message) = self.files.message.take() {
let mut open = true;
let mut done = false;
egui::Window::new("Project file")
.collapsible(false)
.open(&mut open)
.show(ctx, |ui| {
ui.label(&message);
done = ui.button("OK").clicked();
});
if open && !done {
self.files.message = Some(message);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn project_restores_reference_and_editor_and_failed_image_load_keeps_current_work() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let mut bytes = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(2, 2, image::Rgba([20, 50, 80, 255]))
.write_to(&mut bytes, image::ImageFormat::Png)
.unwrap();
let original_bytes = bytes.into_inner();
let file = egui::DroppedFile {
name: "guide.png".into(),
bytes: Some(original_bytes.clone().into()),
..Default::default()
};
app.load_reference(&ctx, &file);
let reference = app.reference.as_mut().unwrap();
reference.opacity = 0.4;
reference.visible = false;
reference.preserve_ratio = true;
app.zoom = 2.5;
app.pan = Vec2::new(-20.5, 40.0);
app.corner = Corner::BottomRight;
app.keep_aspect_ratio = false;
app.show_pattern = true;
let project = Project::from_json(&app.project().to_json().unwrap()).unwrap();
let mut restored = Editor {
edit_content: true,
..Default::default()
};
restored.install_project(&ctx, project.clone()).unwrap();
assert_eq!(restored.project(), project);
assert!(!restored.edit_content);
assert_eq!(restored.reference.as_ref().unwrap().bytes, original_bytes);
let mut broken = project.clone();
broken.output_resolution.width = 3000;
broken.reference.as_mut().unwrap().image_base64 = STANDARD.encode(b"not an image");
assert!(restored.install_project(&ctx, broken).is_err());
assert_eq!(restored.project(), project);
}
}
#[cfg(test)]
mod confirmation_tests {
use super::*;
use crate::gui::tests::{frame, mouse};
fn click_text(app: &mut Editor, ctx: &egui::Context, text: &str) {
frame(app, ctx, vec![]);
let output = frame(app, ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == text => {
Some(t.pos + t.galley.size() / 2.0)
}
_ => None,
})
.expect("confirmation action rendered");
frame(
app,
ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(app, ctx, vec![mouse(pos, false)]);
}
#[test]
fn open_and_overwrite_confirmations_preserve_work_on_cancel() {
let mut app = Editor::default();
let ctx = egui::Context::default();
let original = app.project();
let mut next = original.clone();
next.output_resolution.width = 2560;
next.output_resolution.height = 1440;
app.files.opening = Some((PathBuf::from("candidate.midra.json"), next.clone()));
click_text(&mut app, &ctx, "Cancel");
assert_eq!(app.project(), original);
assert!(app.files.opening.is_none());
app.files.opening = Some((PathBuf::from("candidate.midra.json"), next.clone()));
click_text(&mut app, &ctx, "Open project");
assert_eq!(app.project(), next);
app.files.message = None;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("existing.json");
std::fs::write(&path, b"old contents").unwrap();
app.queue_write(path.clone(), "new contents".into());
assert!(app.files.writing.is_some());
click_text(&mut app, &ctx, "Cancel");
assert_eq!(std::fs::read(&path).unwrap(), b"old contents");
app.queue_write(path.clone(), "new contents".into());
click_text(&mut app, &ctx, "Replace file");
assert_eq!(std::fs::read(&path).unwrap(), b"new contents");
}
}

View File

@ -4,6 +4,7 @@ use std::io::{Cursor, Read};
pub(super) struct Reference {
pub texture: egui::TextureHandle,
pub name: String,
pub bytes: Vec<u8>,
pub size: [u32; 2],
pub visible: bool,
pub opacity: f32,
@ -40,6 +41,7 @@ impl Reference {
Ok(Self {
texture: ctx.load_texture("reference", color, egui::TextureOptions::NEAREST),
name,
bytes,
size,
visible: true,
opacity: 1.0,

View File

@ -0,0 +1,153 @@
use midra_layout::{
Geometry, Layout,
formats::{Crop, Framing, Source},
project::{Project, write_file},
};
#[test]
fn full_precision_project_roundtrip_restores_sources_crops_flags_and_selection() {
let mut layout = Layout::default();
let g = Geometry {
x: -12.123456789,
y: 371.23456789,
width: 300.125,
height: 250.25,
};
let source = Source {
input_crop: Crop {
top: 40.0,
bottom: 40.0,
..Crop::default()
},
..Source::default()
};
layout.configure(1, 0, source, g, true).unwrap();
layout
.set_framing(
1,
Framing {
zoom: 2.25,
offset: [10.0, -15.0],
},
)
.unwrap();
layout.set_visible(0, false);
layout.set_locked(0, true);
layout.set_output([2560, 1600]).unwrap();
let project = Project::from_layout(&layout);
let json = project.to_json().unwrap();
assert!(json.contains("\"advanced_crop\""));
let decoded = Project::from_json(&json).unwrap();
assert_eq!(decoded, project);
let mut loaded = decoded.layout().unwrap();
assert_eq!(loaded.layers(), layout.layers());
assert_eq!(loaded.formats(), layout.formats());
assert!(loaded.locked(0));
assert!(!loaded.visible(0));
assert_eq!(loaded.selection_mask(), layout.selection_mask());
loaded.undo();
assert_eq!(loaded.layers(), layout.layers());
}
#[test]
fn malformed_or_incompatible_projects_are_refused() {
let original = serde_json::to_value(Project::from_layout(&Layout::default())).unwrap();
for (pointer, value) in [
("/version", serde_json::json!(2)),
("/format", serde_json::json!("other")),
("/layers/0/source_id", serde_json::json!(0)),
("/inputs/1/id", serde_json::json!(1)),
("/layers/0/bounds/width", serde_json::json!(-1)),
("/layers/1/advanced_crop/left", serde_json::json!(1900)),
("/editor/selected_layer_ids", serde_json::json!([2, 2])),
("/layers/1/locked", serde_json::json!(true)),
("/editor/viewport_zoom", serde_json::json!(0)),
("/inputs/0/native_resolution/width", serde_json::json!(0)),
] {
let mut invalid = original.clone();
*invalid.pointer_mut(pointer).unwrap() = value;
assert!(
Project::from_json(&invalid.to_string()).is_err(),
"{pointer}"
);
}
let mut extra = original.clone();
extra["unexpected"] = serde_json::json!(true);
assert!(Project::from_json(&extra.to_string()).is_err());
let mut missing = original.clone();
missing.as_object_mut().unwrap().remove("version");
assert!(Project::from_json(&missing.to_string()).is_err());
assert!(Project::from_json("{broken").is_err());
}
#[test]
fn exported_svg_roundtrips_rounded_geometry_including_full_screen_layers() {
let mut layout = Layout::default();
layout
.apply(
0,
Geometry {
x: 0.0,
y: 0.0,
width: 1920.0,
height: 1080.0,
},
)
.unwrap();
layout
.apply(
1,
Geometry {
x: -12.6,
y: 27.4,
width: 300.8,
height: 250.2,
},
)
.unwrap();
layout.set_visible(1, false);
let p = Project::from_layout(&layout);
let doc = midra_layout::import::parse_svg(&p.to_svg(false).unwrap()).unwrap();
assert_eq!(doc.shapes.len(), 2);
assert!(!doc.shapes[0].background);
assert_eq!(doc.shapes[0].geometry, layout.layers()[0]);
assert_eq!(
doc.shapes[1].geometry,
Geometry {
x: -13.0,
y: 27.0,
width: 301.0,
height: 250.0
}
);
assert_eq!(doc.shapes[1].outline, [0.0; 2]);
assert_eq!(
midra_layout::import::parse_svg(&p.to_svg(true).unwrap())
.unwrap()
.shapes
.len(),
1
);
layout.set_visible(0, false);
assert!(Project::from_layout(&layout).to_svg(true).is_err());
}
#[test]
fn publication_requires_overwrite_and_read_matches_written_document() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("layout.midra.json");
let p = Project::from_layout(&Layout::default());
write_file(&path, p.to_json().unwrap().as_bytes(), false).unwrap();
assert_eq!(Project::read(&path).unwrap(), p);
assert!(write_file(&path, b"replacement", false).is_err());
assert_eq!(Project::read(&path).unwrap(), p);
write_file(&path, b"replacement", true).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"replacement");
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
}
#[test]
fn documented_example_is_a_valid_version_one_project() {
let example = include_str!("../../../docs/interfaces/midra-layout-v1.example.json");
assert_eq!(
Project::from_json(example).unwrap(),
Project::from_layout(&Layout::default())
);
}

View File

@ -0,0 +1,90 @@
{
"format": "beffroi.midra-layout",
"version": 1,
"output_resolution": {
"width": 1920,
"height": 1080
},
"inputs": [
{
"id": 1,
"source_format": "sixteen_nine",
"native_resolution": {
"width": 1920,
"height": 1080
},
"input_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
}
},
{
"id": 2,
"source_format": "sixteen_nine",
"native_resolution": {
"width": 1920,
"height": 1080
},
"input_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
}
}
],
"layers": [
{
"id": 1,
"source_id": 1,
"bounds": {
"x": 120.0,
"y": 180.0,
"width": 640.0,
"height": 360.0
},
"advanced_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
},
"visible": true,
"locked": false
},
{
"id": 2,
"source_id": 2,
"bounds": {
"x": 1160.0,
"y": 180.0,
"width": 640.0,
"height": 360.0
},
"advanced_crop": {
"left": 0.0,
"right": 0.0,
"top": 0.0,
"bottom": 0.0
},
"visible": true,
"locked": false
}
],
"reference": null,
"editor": {
"selected_layer_ids": [
2
],
"position_corner": "top_left",
"keep_aspect_ratio": true,
"viewport_zoom": 1.0,
"viewport_pan": [
0.0,
0.0
],
"show_source_pattern": false
}
}

View File

@ -0,0 +1,146 @@
# Midra Layout file interfaces
These are offline editor formats, not Analog Way REST payloads. Implementation:
[`project.rs`](../../crates/midra-layout/src/project.rs). Regression tests:
[`project.rs`](../../crates/midra-layout/tests/project.rs). Update this contract,
examples and tests in the same change as any save/export schema change.
## Project JSON, version 1
Suggested filename: `layout.midra.json`. Encoding: UTF-8, pretty-printed JSON,
with a trailing newline. A project preserves applied document values at their
stored floating-point precision. No display rounding is applied. The loader
requires every field below, rejects unknown fields, and rejects unsupported
versions. It does not guess, migrate, or partially apply incompatible files.
[Complete example](midra-layout-v1.example.json) is a valid default project,
without a reference image. It is loaded by the regression tests.
| Root field | Representation / meaning |
| --- | --- |
| `format` | Exactly `"beffroi.midra-layout"` |
| `version` | Integer `1` |
| `output_resolution` | `{ "width": integer, "height": integer }`, screen pixels |
| `inputs` | Exactly two input objects, IDs 1 and 2, in that order |
| `layers` | Exactly two layer objects, IDs 1 and 2, in that order |
| `reference` | `null` or an embedded reference-image object |
| `editor` | Selection, positioning and viewport preferences |
Input objects:
| Field | Representation / meaning |
| --- | --- |
| `id` | Input slot 1 or 2; not an external device identifier |
| `source_format` | `"four_three"`, `"sixteen_nine"`, `"sixteen_ten"`, `"square"`, or `"custom"` |
| `native_resolution` | `{ "width": integer, "height": integer }`, native input pixels |
| `input_crop` | `{ "left": number, "right": number, "top": number, "bottom": number }`, pixels removed from the native input |
The user-facing input resolution is derived by subtracting opposite input crop
edges from native dimensions. The source format remains explicit even with
custom input cropping. Non-custom source formats must match the native resolution
within the existing half-pixel rounding tolerance.
Layer objects:
| Field | Representation / meaning |
| --- | --- |
| `id` | Editor layer slot 1 or 2; independent of future Midra mapping |
| `source_id` | Input ID 1 or 2; both layers may share an input |
| `bounds` | `{ "x": number, "y": number, "width": number, "height": number }`, final visible box in screen pixels; x/y are its top-left position |
| `advanced_crop` | Four nonnegative edges in usable input pixels, after input cropping |
| `visible` | Boolean editor visibility |
| `locked` | Boolean editor selection/movement protection |
The visible box is the user's layer resolution. Its content zoom and offset are
**derived** from `advanced_crop`, usable input size and visible box size; they are
not duplicated in the save file. Retained source pixels must have the same ratio
as the box. Crop zoom must be 1–100 (100–10000%). Shared input assignments and
both crop stages survive round trips without rewriting the crop values.
Reference object:
| Field | Representation / meaning |
| --- | --- |
| `name` | Display filename, not a path to read |
| `image_base64` | Standard padded RFC 4648 base64 of the original PNG/JPEG/BMP file bytes; no data-URL prefix |
| `visible` | Boolean |
| `opacity` | Number from 0 to 1 |
| `preserve_ratio` | Boolean: fit proportionally if true, stretch to screen if false |
The image is embedded, so moving the project does not break the reference. No
external files, URLs or device endpoints are accessed on load. Image dimensions
are decoded from the bytes. The existing image loader enforces a 64 MiB encoded
file limit, maximum 8192 pixels per side (or the GPU texture limit if smaller),
and a 256 MiB decoder allocation limit. Bad image data aborts opening and leaves
the current editor unchanged.
Editor object:
| Field | Representation / meaning |
| --- | --- |
| `selected_layer_ids` | Array of unique IDs of visible, unlocked layers; may be empty |
| `position_corner` | `"top_left"`, `"top_right"`, `"bottom_left"`, `"bottom_right"` |
| `keep_aspect_ratio` | Boolean for layer resizing |
| `viewport_zoom` | Positive fit-relative scale, 0.0001–256 |
| `viewport_pan` | `[x, y]`, viewport pan in screen-coordinate pixels; finite, absolute value at most 1e9 |
| `show_source_pattern` | Boolean source-coordinate preview setting |
Resolution dimensions must be whole pixels from 1 to 16384. Layer x/y must be finite and within ±1,000,000 pixels; layer widths/heights
and retained input dimensions must be positive, finite, and at most 1,000,000
pixels. Crop edges must be finite and nonnegative, with a positive retained
region. Off-screen x/y are allowed. Invalid source references, duplicate/out-of-order IDs, invalid crops,
missing fields and non-finite values are rejected before replacing the document.
Projects larger than 96 MiB are rejected.
Save includes **applied values only**. Pending text/format/import drafts, open
dialogs, undo/redo history, crop-edit mode, resize mode, and provisional device
export calculations are not persisted. Current layer names are fixed by editor
slot and are not stored. Loading starts a fresh history. Loading requires a
replacement confirmation; failed loading leaves current work intact. Writes use
a same-directory temporary file and atomic publication. Existing destination
files require explicit replacement confirmation. A failed no-overwrite write
leaves the existing file intact.
## SVG geometry exchange, version 1
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
`data-midra-layout-geometry="1"`. A title and one `<rect>` per exported layer follow.
```xml
<svg xmlns="http://www.w3.org/2000/svg" data-midra-layout-geometry="1"
width="1920" height="1080" viewBox="0 0 1920 1080">
<title>Midra Layout geometry</title>
<rect id="layer-1" x="120" y="180" width="640" height="360" fill="#173b50"/>
<rect id="layer-2" x="1160" y="180" width="640" height="360" fill="#173b50"/>
</svg>
```
- IDs are stable editor-slot names `layer-1`, `layer-2`; rectangle order is slot
order, independent of viewport selection/foreground drawing.
- Coordinates are the visible box top-left and size, rounded independently to
nearest whole pixels; half values round away from zero. Negative coordinates
are retained. Dimensions that would round to zero reject export.
- There are no strokes, transforms or groups, so stroke expansion is unnecessary.
- **All layers** includes hidden and locked layers as ordinary visible rectangles.
**Visible layers only** omits hidden layers but includes locked visible ones.
An empty visible selection rejects export instead of producing an unimportable file.
- The file is a geometry interchange, not a project backup. It deliberately omits
source assignments, crops, content zoom, reference image, lock/visibility flags,
selection and camera. Use project JSON to preserve those.
- Select the same number of destination layers, then use **Import → SVG file**
and review the mappings. A full-screen rectangle bearing this export marker
is treated as a layer, not an automatically ignored background. Other SVGs keep
the existing full-page background detection rule.
- Reimporting restores rounded box geometry through the regular import options;
it does not set the screen resolution or restore omitted project state. External
SVG editors may remove the marker; then review the background checkbox on import.
## Compatibility changes
Version 1 is a strict contract. 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
with every schema or semantic change, including additive fields under the strict
unknown-field policy. Never silently interpret a future version as version 1.

View File

@ -380,3 +380,22 @@ content corner stays anchored where possible; offsets clamp to keep the visible
box filled when zooming out. Zoom is limited to 100–10000%. Drag the image to pan
its content. Each zoom gesture is one undo step; Escape cancels an active gesture.
Use viewport zoom/pan to reach content handles beyond the current view.
## Save, open and export
Use the **Project** toolbar menu to **Save project…** or **Open project…**.
Projects use readable, versioned `.midra.json` files and preserve applied output,
inputs, layer bounds/crops, source assignments, locks, visibility, selection,
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 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.
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).