Add draw.io geometry paste and interactive Midra layer positioning

This commit is contained in:
Dandaedre 2026-11-13 11:44:31 +01:00
parent 6cd65d3ac5
commit 9058801b02
10 changed files with 1699 additions and 232 deletions

1
Cargo.lock generated
View File

@ -2396,6 +2396,7 @@ name = "midra-layout"
version = "0.3.0"
dependencies = [
"eframe",
"roxmltree",
]
[[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 appearance preview](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)
- [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

@ -4,7 +4,8 @@ version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
description = "Offline Midra layer layout helper — appearance preview"
description = "Offline Midra layer positioning and draw.io geometry import"
[dependencies]
roxmltree = "0.20"
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "x11", "wayland"] }

View File

@ -0,0 +1,990 @@
use super::*;
use midra_layout::{Corner, DrawioShape, Geometry, Layout, parse_drawio};
pub struct Editor {
layout: Layout,
corner: Corner,
fields: [String; 4],
error: String,
paste: Option<Paste>,
zoom: f32,
pan: Vec2,
panning: bool,
}
struct Paste {
target: usize,
text: String,
shapes: Vec<DrawioShape>,
choice: usize,
include_size: bool,
error: String,
}
impl Paste {
fn parse(&mut self) {
self.choice = 0;
match parse_drawio(&self.text) {
Ok(shapes) => {
self.shapes = shapes;
self.error.clear();
}
Err(error) => {
self.shapes.clear();
self.error = error;
}
}
}
}
impl Default for Editor {
fn default() -> Self {
let mut this = Self {
layout: Layout::default(),
corner: Corner::TopRight,
fields: Default::default(),
error: String::new(),
paste: None,
zoom: 1.0,
pan: Vec2::ZERO,
panning: false,
};
this.sync();
this
}
}
fn number(n: f64) -> String {
n.to_string()
}
fn label(i: usize) -> &'static str {
if i == 0 {
"01 / Presenter"
} else {
"02 / Slides"
}
}
fn bounds(g: Geometry) -> String {
format!(
"X {} · Y {}\n{} × {} px",
number(g.x),
number(g.y),
number(g.width),
number(g.height)
)
}
impl Editor {
fn sync(&mut self) {
if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
let [x, y] = self.corner.offsets(g);
self.fields = [number(x), number(y), number(g.width), number(g.height)];
}
self.error.clear();
}
fn open_paste(&mut self, text: String) {
if let Some(target) = self.layout.selected() {
let mut p = Paste {
target,
text,
shapes: Vec::new(),
choice: 0,
include_size: true,
error: String::new(),
};
if !p.text.is_empty() {
p.parse();
}
self.paste = Some(p);
} else {
self.error = "Select a layer before pasting.".into();
}
}
fn apply_fields(&mut self) {
let values: Result<Vec<f64>, _> = self
.fields
.iter()
.map(|s| s.trim().parse::<f64>())
.collect();
let result = values
.map_err(|_| "Enter a number in each field.".to_string())
.and_then(|v| self.corner.geometry(v[0], v[1], v[2], v[3]));
match result {
Ok(g) => {
if let Some(i) = self.layout.selected() {
match self.layout.apply(i, g) {
Ok(()) => self.sync(),
Err(e) => self.error = e,
}
}
}
Err(e) => self.error = e,
}
}
fn copy(&self, ctx: &egui::Context) {
if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
let [h, v] = g.center();
ctx.copy_text(format!(
"{}\nHorizontal: {} px\nVertical: {} px\nWidth: {} px\nHeight: {} px",
label(i),
number(h),
number(v),
number(g.width),
number(g.height)
));
}
}
fn shortcuts(&mut self, ctx: &egui::Context) {
if self.paste.is_some() {
return;
}
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
self.layout.cancel_drag();
self.sync();
ctx.memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
}
});
return;
}
if ctx.wants_keyboard_input() {
return;
}
let paste = ctx.input_mut(|i| {
let mut pasted = None;
i.events.retain(|e| {
if let egui::Event::Paste(s) = e {
pasted = Some(s.clone());
false
} else {
true
}
});
pasted
});
if let Some(text) = paste {
self.open_paste(text);
return;
}
if self.layout.dragging() {
return;
}
let command = ctx.input(|i| i.modifiers.command);
if command {
if ctx.input(|i| i.key_pressed(egui::Key::Z)) {
if ctx.input(|i| i.modifiers.shift) {
self.layout.redo();
} else {
self.layout.undo();
}
self.sync();
} else if ctx.input(|i| i.key_pressed(egui::Key::Y)) {
self.layout.redo();
self.sync();
}
return;
}
let step = if ctx.input(|i| i.modifiers.shift) {
10.0
} else {
1.0
};
let mut d = [0.0, 0.0];
for (key, axis, sign) in [
(egui::Key::ArrowLeft, 0, -1.0),
(egui::Key::ArrowRight, 0, 1.0),
(egui::Key::ArrowUp, 1, -1.0),
(egui::Key::ArrowDown, 1, 1.0),
] {
if ctx.input(|i| i.key_pressed(key)) {
d[axis] += sign * step;
}
}
if d != [0.0, 0.0] {
match self.layout.nudge(d[0], d[1]) {
Ok(()) => self.sync(),
Err(e) => self.error = e,
}
}
}
fn paste_window(&mut self, ctx: &egui::Context) {
let Some(mut p) = self.paste.take() else {
return;
};
let mut close = false;
let response = egui::Modal::new(egui::Id::new("drawio-paste")).show(ctx, |ui| {
ui.set_width(530.0);
ui.heading("Paste draw.io geometry");
ui.label(format!("Target: {}", label(p.target)));
ui.label("1 draw.io unit = 1 screen pixel · top-left origin");
ui.label("Paste encoded clipboard text or raw mxGraphModel XML:");
if ui
.add(
egui::TextEdit::multiline(&mut p.text)
.desired_rows(4)
.desired_width(f32::INFINITY),
)
.changed()
{
p.shapes.clear();
p.error.clear();
}
if ui.button("Read geometry").clicked() {
p.parse();
}
if !p.error.is_empty() {
ui.colored_label(AMBER, &p.error);
}
if !p.shapes.is_empty() {
if p.shapes.len() > 1 {
egui::ComboBox::from_label("Rectangle")
.selected_text(&p.shapes[p.choice].id)
.show_ui(ui, |ui| {
for (i, s) in p.shapes.iter().enumerate() {
ui.selectable_value(
&mut p.choice,
i,
format!(
"Cell {} · {} × {}",
s.id, s.geometry.width, s.geometry.height
),
);
}
});
}
ui.checkbox(
&mut p.include_size,
"Include size / format (otherwise position only)",
);
let before = self.layout.layers()[p.target];
let mut after = p.shapes[p.choice].geometry;
if !p.include_size {
after.width = before.width;
after.height = before.height;
}
ui.separator();
ui.columns(2, |cols| {
cols[0].label("Before");
cols[0].label(bounds(before));
cols[1].label("After");
cols[1].label(bounds(after));
});
if after.outside() {
ui.colored_label(
AMBER,
"This rectangle extends outside the screen. Its coordinates are preserved.",
);
}
ui.label("Geometry only; source format, colors and stroke are not imported.");
if ui
.add(egui::Button::new("Apply to selected target").fill(PURPLE))
.clicked()
{
match self.layout.apply(p.target, after) {
Ok(()) => {
self.sync();
close = true;
}
Err(e) => p.error = e,
}
}
}
if ui.button("Cancel").clicked() {
close = true;
}
});
if !close && !response.should_close() {
self.paste = Some(p);
}
}
fn inspector(&mut self, ui: &mut egui::Ui) {
let (r, _) =
ui.allocate_exact_size(Vec2::new(ui.available_width(), 920.0), egui::Sense::hover());
let ink = Ink::new(ui, r);
let w = r.width();
ink.text(0.0, 2.0, "LAYERS", 11.0, MUTED);
for i in 0..2 {
let y = 28.0 + i as f32 * 44.0;
let color = if i == 0 { AMBER } else { CYAN };
ink.card(
0.0,
y,
w,
38.0,
FIELD,
if self.layout.selected() == Some(i) {
color
} else {
LINE
},
);
ink.text(13.0, y + 10.0, label(i), 15.0, color);
if click(ui, &ink, [0.0, y, w, 38.0], ("layer", i)) {
self.layout.select(Some(i));
self.sync();
}
}
ink.line([0.0, 130.0], [w, 130.0], LINE);
let Some(i) = self.layout.selected() else {
ink.text(0.0, 153.0, "Select a layer to edit or paste.", 17.0, TEXT);
return;
};
let g = self.layout.layers()[i];
ink.text(0.0, 150.0, label(i), 25.0, TEXT);
ink.text(0.0, 191.0, "LAYER FORMAT / VISIBLE BOX", 11.0, MUTED);
ink.card(0.0, 214.0, w, 34.0, FIELD, LINE);
ink.text(
12.0,
223.0,
&format!(
"{} × {} px / {:.4}:1",
number(g.width),
number(g.height),
g.width / g.height
),
13.0,
TEXT,
);
ink.text(0.0, 267.0, "POSITION FROM SCREEN CORNER", 11.0, MUTED);
ink.card(0.0, 292.0, 94.0, 58.0, FIELD, LINE);
for (x, y, c) in [
(8.0, 300.0, Corner::TopLeft),
(84.0, 300.0, Corner::TopRight),
(8.0, 342.0, Corner::BottomLeft),
(84.0, 342.0, Corner::BottomRight),
] {
ink.rect(
x - 3.0,
y - 3.0,
6.0,
6.0,
if c == self.corner { CYAN } else { MUTED },
);
if click(
ui,
&ink,
[x - 10.0, y - 10.0, 20.0, 20.0],
format!("corner-{c:?}"),
) {
self.corner = c;
self.sync();
}
}
let (name, horizontal, vertical) = match self.corner {
Corner::TopLeft => ("Top left", "From left", "From top"),
Corner::TopRight => ("Top right", "From right", "From top"),
Corner::BottomLeft => ("Bottom left", "From left", "From bottom"),
Corner::BottomRight => ("Bottom right", "From right", "From bottom"),
};
ink.text(112.0, 299.0, name, 18.0, TEXT);
ink.text(112.0, 326.0, "Offsets inward · px", 12.0, MUTED);
let half = (w - 12.0) / 2.0;
let mut enter = false;
for (index, x, y, title) in [
(0, 0.0, 368.0, horizontal),
(1, half + 12.0, 368.0, vertical),
(2, 0.0, 449.0, "Layer width"),
(3, half + 12.0, 449.0, "Layer height"),
] {
ink.text(x, y, title, 12.0, MUTED);
let rect = Rect::from_min_size(ink.point(x, y + 23.0), Vec2::new(half, 42.0));
let response = ui.put(
rect,
egui::TextEdit::singleline(&mut self.fields[index])
.id(egui::Id::new(("geometry", index)))
.font(egui::FontId::proportional(18.0))
.margin(Vec2::new(12.0, 10.0)),
);
if response.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {
enter = true;
}
}
ink.button(0.0, 530.0, w, "Apply position / size", false);
if click(ui, &ink, [0.0, 530.0, w, 34.0], "apply-fields") || enter {
self.apply_fields();
}
if !self.error.is_empty() {
ui.put(
Rect::from_min_size(ink.point(0.0, 575.0), Vec2::new(w, 55.0)),
egui::Label::new(egui::RichText::new(&self.error).color(AMBER)).wrap(),
);
} else if g.outside() {
ink.text(
0.0,
579.0,
"Outside screen · use Fit layer to find it",
12.0,
AMBER,
);
}
ink.line([0.0, 612.0], [w, 612.0], LINE);
ink.text(0.0, 635.0, "WEBRCS / CENTER POSITION", 11.0, CYAN);
let [h, v] = g.center();
ink.field(0.0, 665.0, half, "Horizontal · from left", &number(h));
ink.field(half + 12.0, 665.0, half, "Vertical · from top", &number(v));
ink.text(
0.0,
748.0,
"Center convention · device precision unverified",
12.0,
MUTED,
);
ink.button(0.0, 780.0, w, "Copy position values", true);
if click(ui, &ink, [0.0, 780.0, w, 34.0], "copy-values") {
self.copy(ui.ctx());
}
ink.button(0.0, 829.0, w, "Paste draw.io…", false);
if click(ui, &ink, [0.0, 829.0, w, 34.0], "paste-button") {
self.open_paste(String::new());
}
ink.text(
0.0,
884.0,
"Or Ctrl/Cmd-V with the viewport focused",
12.0,
MUTED,
);
}
fn workspace(&mut self, ui: &mut egui::Ui) {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
ink.button(24.0, 20.0, 185.0, "Screen 1 · Full HD", false);
ink.text(224.0, 30.0, "1920 × 1080 · fixed for now", 12.0, MUTED);
for (x, w, text) in [
(24.0, 103.0, "Fit screen"),
(139.0, 91.0, "Fit layer"),
(242.0, 80.0, "Undo"),
(334.0, 80.0, "Redo"),
] {
ink.button(x, 67.0, w, text, false);
if click(ui, &ink, [x, 67.0, w, 34.0], text) {
match text {
"Fit screen" => {
self.zoom = 1.0;
self.pan = Vec2::ZERO;
}
"Fit layer" => {
if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
self.zoom = (1920.0 / g.width).min(1080.0 / g.height) as f32 * 0.8;
self.zoom = self.zoom.clamp(0.02, 32.0);
let c = g.center();
self.pan = Vec2::new(960.0 - c[0] as f32, 540.0 - c[1] as f32);
}
}
"Undo" => {
self.layout.undo();
self.sync();
}
_ => {
self.layout.redo();
self.sync();
}
}
}
}
ink.button(426.0, 67.0, 154.0, "Paste draw.io…", true);
if click(ui, &ink, [426.0, 67.0, 154.0, 34.0], "toolbar-paste") {
self.open_paste(String::new());
}
ink.text(25.0, 132.0, "YOUR SCREEN, PRECISELY PLACED", 12.0, CYAN);
ink.text(25.0, 157.0, "Select. Paste. Place.", 17.0, MUTED);
let area = Rect::from_min_max(
r.min + Vec2::new(20.0, 204.0),
r.max - Vec2::new(20.0, 85.0),
);
let base = ((area.width() - 48.0) / 1920.0).min((area.height() - 48.0) / 1080.0);
let mut scale = base * self.zoom;
let mut origin = area.center() - Vec2::new(960.0, 540.0) * scale + self.pan * scale;
let response = ui.interact(area, egui::Id::new("canvas"), egui::Sense::click_and_drag());
let pointer = ui.input(|i| i.pointer.interact_pos());
if response.hovered() && !self.layout.dragging() && !self.panning {
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
if scroll != 0.0
&& let Some(p) = pointer
{
let world = (p - origin) / scale;
self.zoom = (self.zoom * (scroll * 0.002).exp()).clamp(0.02, 32.0);
scale = base * self.zoom;
self.pan = (p - area.center()) / scale + Vec2::new(960.0, 540.0) - world;
origin = area.center() - Vec2::new(960.0, 540.0) * scale + self.pan * scale;
}
}
if response.drag_started() {
ui.ctx().memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
}
});
self.panning = ui.input(|i| {
i.key_down(egui::Key::Space) || i.pointer.button_down(egui::PointerButton::Middle)
});
if !self.panning
&& let Some(p) = ui.input(|i| i.pointer.press_origin())
{
let p = (p - origin) / scale;
self.layout.start_drag([p.x as f64, p.y as f64]);
self.sync();
}
}
if response.dragged() {
if self.panning {
self.pan += response.drag_delta() / scale;
origin += response.drag_delta();
} else if let Some(p) = pointer {
let p = (p - origin) / scale;
self.layout.drag_to([p.x as f64, p.y as f64]);
self.sync();
}
}
if response.drag_stopped() {
if self.layout.dragging()
&& let Some(p) = pointer
{
let p = (p - origin) / scale;
self.layout.drag_to([p.x as f64, p.y as f64]);
self.sync();
}
self.layout.finish_drag();
self.panning = false;
}
if response.clicked()
&& let Some(p) = pointer
{
let p = (p - origin) / scale;
self.layout
.select(self.layout.hit([p.x as f64, p.y as f64]));
self.sync();
ui.ctx().memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
}
});
}
let screen = Ink {
painter: ui.painter_at(area),
origin,
scale: scale * 2.0,
};
screen_artwork(&screen);
for (i, g) in self.layout.layers().iter().enumerate() {
let color = if i == 0 { AMBER } else { CYAN };
let rect = Rect::from_min_size(
origin + Vec2::new(g.x as f32, g.y as f32) * scale,
Vec2::new(g.width as f32, g.height as f32) * scale,
);
let p = &screen.painter;
p.rect(
rect,
0.0,
Color32::from_rgb(23, 59, 80),
Stroke::new(1.0_f32, color),
StrokeKind::Inside,
);
if rect.width() > 85.0 && rect.height() > 40.0 {
let clipped = p.with_clip_rect(area.intersect(rect.shrink(5.0)));
clipped.text(
rect.min + Vec2::splat(12.0),
Align2::LEFT_TOP,
label(i),
FontId::proportional(13.0),
color,
);
if rect.height() > 75.0 {
clipped.text(
rect.left_bottom() + Vec2::new(12.0, -20.0),
Align2::LEFT_BOTTOM,
format!("{} × {} px", number(g.width), number(g.height)),
FontId::proportional(12.0),
TEXT,
);
}
}
if self.layout.selected() == Some(i) {
for corner in [
rect.left_top(),
rect.right_top(),
rect.left_bottom(),
rect.right_bottom(),
] {
p.rect(
Rect::from_center_size(corner, Vec2::splat(7.0)),
1.0,
PANEL,
Stroke::new(1.0_f32, color),
StrokeKind::Inside,
);
}
p.line_segment(
[
rect.center() - Vec2::new(7.0, 0.0),
rect.center() + Vec2::new(7.0, 0.0),
],
Stroke::new(1.0_f32, color),
);
p.line_segment(
[
rect.center() - Vec2::new(0.0, 7.0),
rect.center() + Vec2::new(0.0, 7.0),
],
Stroke::new(1.0_f32, color),
);
}
}
if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
if !g.outside() {
let [dx, dy] = self.corner.offsets(g);
let right = matches!(self.corner, Corner::TopRight | Corner::BottomRight);
let bottom = matches!(self.corner, Corner::BottomLeft | Corner::BottomRight);
let edge = origin
+ Vec2::new(
if right {
(g.x + g.width) as f32
} else {
g.x as f32
},
if bottom {
(g.y + g.height) as f32
} else {
g.y as f32
},
) * scale;
let boundary = origin
+ Vec2::new(
if right { 1920.0 } else { 0.0 },
if bottom { 1080.0 } else { 0.0 },
) * scale;
let guide = &screen.painter;
let stroke = Stroke::new(1.0_f32, CYAN);
guide.line_segment(
[
edge + Vec2::new(0.0, 16.0),
Pos2::new(boundary.x, edge.y + 16.0),
],
stroke,
);
guide.line_segment(
[
edge + Vec2::new(14.0, 0.0),
Pos2::new(edge.x + 14.0, boundary.y),
],
stroke,
);
guide.text(
Pos2::new((edge.x + boundary.x) / 2.0, edge.y + 22.0),
Align2::CENTER_TOP,
format!("{dx:.2} px"),
FontId::proportional(11.0),
CYAN,
);
guide.text(
Pos2::new(edge.x + 20.0, (edge.y + boundary.y) / 2.0),
Align2::LEFT_CENTER,
format!("{dy:.2} px"),
FontId::proportional(11.0),
CYAN,
);
}
}
ink.text(
24.0,
r.height() - 57.0,
"Drag layer · Arrows 1 px · Shift 10 px · Ctrl/Cmd-V paste",
12.0,
MUTED,
);
ink.text(
24.0,
r.height() - 31.0,
"Scroll to zoom · Space-drag to pan · Background is illustrative",
12.0,
MUTED,
);
}
}
fn click(ui: &egui::Ui, ink: &Ink, b: [f32; 4], id: impl std::hash::Hash) -> bool {
let clicked = ui
.interact(
Rect::from_min_size(ink.point(b[0], b[1]), Vec2::new(b[2], b[3])),
egui::Id::new(id),
egui::Sense::click(),
)
.on_hover_cursor(egui::CursorIcon::PointingHand)
.clicked();
if clicked {
ui.ctx().memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
}
});
}
clicked
}
impl Editor {
fn ui(&mut self, ctx: &egui::Context) {
self.shortcuts(ctx);
egui::TopBottomPanel::top("header")
.exact_height(64.0)
.frame(egui::Frame::NONE.fill(PANEL))
.show(ctx, |ui| {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
ink.text(24.0, 21.0, "MIDRA / LAYOUT", 21.0, TEXT);
ink.line([218.0, 22.0], [218.0, 43.0], LINE);
ink.text(238.0, 26.0, "Offline position helper", 13.0, MUTED);
ink.text(r.width() - 347.0, 27.0, "EIKOS 4K", 12.0, CYAN);
ink.button(r.width() - 212.0, 15.0, 188.0, "Copy coordinates", false);
if click(
ui,
&ink,
[r.width() - 212.0, 15.0, 188.0, 34.0],
"header-copy",
) {
self.copy(ctx);
}
});
egui::TopBottomPanel::bottom("status")
.exact_height(34.0)
.frame(egui::Frame::NONE.fill(PANEL))
.show(ctx, |ui| {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
ink.painter.circle_filled(ink.point(24.0, 17.0), 3.0, CYAN);
ink.text(36.0, 10.0, "OFFLINE", 11.0, MUTED);
ink.text(
116.0,
10.0,
if self.layout.selected().is_some() {
"draw.io geometry · 1 unit = 1 px"
} else {
"Select a layer to move or paste"
},
12.0,
MUTED,
);
ink.text(
r.width() - 278.0,
10.0,
"Screen pixels / 1920 × 1080",
12.0,
MUTED,
);
});
egui::SidePanel::right("inspector")
.exact_width(392.0)
.resizable(false)
.frame(egui::Frame::NONE.fill(PANEL).inner_margin(24.0))
.show(ctx, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| self.inspector(ui));
});
egui::CentralPanel::default()
.frame(egui::Frame::NONE.fill(BG))
.show(ctx, |ui| self.workspace(ui));
self.paste_window(ctx);
}
}
impl eframe::App for Editor {
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
self.ui(ctx);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn frame(app: &mut Editor, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::FullOutput {
let input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(1440.0, 940.0))),
events,
..Default::default()
};
ctx.run(input, |ctx| app.ui(ctx))
}
fn key(key: egui::Key) -> egui::Event {
egui::Event::Key {
key,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}
}
#[test]
fn paste_opens_review_without_editing_and_escape_cancels() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let before = *app.layout.layers();
frame(
&mut app,
&ctx,
vec![egui::Event::Paste(
include_str!("../tests/fixtures/drawio-rectangle.txt").into(),
)],
);
assert_eq!(*app.layout.layers(), before);
let p = app.paste.as_ref().unwrap();
assert_eq!(p.target, 1);
assert_eq!(p.shapes[0].geometry.width, 945.0);
frame(&mut app, &ctx, vec![key(egui::Key::Escape)]);
assert!(app.paste.is_none());
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn numeric_focus_keeps_paste_out_of_importer_and_arrows_out_of_geometry() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
ctx.memory_mut(|m| m.request_focus(egui::Id::new(("geometry", 0_usize))));
frame(&mut app, &ctx, vec![]);
assert!(ctx.wants_keyboard_input());
let before = *app.layout.layers();
frame(
&mut app,
&ctx,
vec![egui::Event::Paste("123".into()), key(egui::Key::ArrowLeft)],
);
assert!(app.paste.is_none());
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn invalid_numeric_edits_preserve_document_and_valid_edits_are_reversible() {
let mut app = Editor::default();
let before = *app.layout.layers();
app.fields = ["0".into(), "0".into(), "NaN".into(), "300".into()];
app.apply_fields();
assert!(!app.error.is_empty());
assert_eq!(*app.layout.layers(), before);
app.fields = ["120".into(), "180".into(), "945".into(), "531.58".into()];
app.apply_fields();
assert!(app.error.is_empty());
assert_eq!(app.layout.layers()[1].width, 945.0);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn paste_without_selection_and_invalid_xml_do_not_edit() {
let mut app = Editor::default();
let before = *app.layout.layers();
app.layout.select(None);
app.open_paste("invalid".into());
assert!(app.paste.is_none());
assert!(!app.error.is_empty());
app.layout.select(Some(0));
app.open_paste("invalid".into());
assert!(app.paste.as_ref().unwrap().shapes.is_empty());
assert!(!app.paste.as_ref().unwrap().error.is_empty());
assert_eq!(*app.layout.layers(), before);
}
fn mouse(p: Pos2, pressed: bool) -> egui::Event {
egui::Event::PointerButton {
pos: p,
button: egui::PointerButton::Primary,
pressed,
modifiers: egui::Modifiers::NONE,
}
}
#[test]
fn modal_apply_button_imports_exact_sample_and_undo_restores() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let before = *app.layout.layers();
frame(
&mut app,
&ctx,
vec![egui::Event::Paste(
include_str!("../tests/fixtures/drawio-rectangle.txt").into(),
)],
);
let output = frame(&mut app, &ctx, vec![]);
let position = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::epaint::Shape::Text(t) if t.galley.job.text == "Apply to selected target" => {
Some(t.pos + Vec2::new(30.0, 6.0))
}
_ => None,
})
.expect("Apply button rendered");
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(position), mouse(position, true)],
);
frame(&mut app, &ctx, vec![mouse(position, false)]);
assert!(app.paste.is_none());
assert_eq!(app.layout.layers()[1].x, 12.0);
assert_eq!(app.layout.layers()[1].height, 531.58);
assert_eq!(app.layout.layers()[0], before[0]);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn pointer_drag_is_one_edit_and_does_not_move_other_layer() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let before = *app.layout.layers();
let start = Pos2::new(700.0, 420.0);
let end = start + Vec2::new(40.0, 20.0);
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start), mouse(start, true)],
);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
frame(&mut app, &ctx, vec![mouse(end, false)]);
assert_eq!(app.layout.layers()[0], before[0]);
assert!(app.layout.layers()[1].x > before[1].x);
assert!(app.layout.layers()[1].y > before[1].y);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn list_selection_then_paste_targets_that_layer() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let p = Pos2::new(1180.0, 135.0);
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(p), mouse(p, true)],
);
frame(&mut app, &ctx, vec![mouse(p, false)]);
assert_eq!(app.layout.selected(), Some(0));
frame(
&mut app,
&ctx,
vec![egui::Event::Paste(
include_str!("../tests/fixtures/drawio-rectangle.txt").into(),
)],
);
assert_eq!(app.paste.as_ref().unwrap().target, 0);
}
#[test]
fn zoom_changes_camera_without_geometry_or_undo_edits() {
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
let before = *app.layout.layers();
frame(
&mut app,
&ctx,
vec![
egui::Event::PointerMoved(Pos2::new(700.0, 420.0)),
egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: Vec2::new(0.0, 100.0),
modifiers: egui::Modifiers::NONE,
},
],
);
assert!(app.zoom > 1.0);
assert_eq!(*app.layout.layers(), before);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
}

View File

@ -0,0 +1,345 @@
//! Offline layer geometry, reversible edits and a deliberately narrow draw.io adapter.
use std::collections::HashMap;
/// Visible layer bounds, in output screen pixels. No crop or camera transform.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Geometry {
pub x: f64,
pub y: f64,
pub width: f64,
pub height: f64,
}
impl Geometry {
pub fn validate(self) -> Result<Self, String> {
if [self.x, self.y, self.width, self.height]
.iter()
.any(|n| !n.is_finite() || n.abs() > 1_000_000.0)
|| self.width <= 0.0
|| self.height <= 0.0
{
return Err("Use finite coordinates within ±1,000,000 px and positive sizes up to 1,000,000 px.".into());
}
Ok(self)
}
pub fn center(self) -> [f64; 2] {
[self.x + self.width / 2.0, self.y + self.height / 2.0]
}
pub fn contains(self, p: [f64; 2]) -> bool {
p[0] >= self.x
&& p[0] <= self.x + self.width
&& p[1] >= self.y
&& p[1] <= self.y + self.height
}
pub fn outside(self) -> bool {
self.x < 0.0
|| self.y < 0.0
|| self.x + self.width > 1920.0
|| self.y + self.height > 1080.0
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Corner {
#[default]
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl Corner {
pub fn offsets(self, g: Geometry) -> [f64; 2] {
[
if matches!(self, Self::TopRight | Self::BottomRight) {
1920.0 - g.x - g.width
} else {
g.x
},
if matches!(self, Self::BottomLeft | Self::BottomRight) {
1080.0 - g.y - g.height
} else {
g.y
},
]
}
pub fn geometry(self, dx: f64, dy: f64, width: f64, height: f64) -> Result<Geometry, String> {
Geometry {
x: if matches!(self, Self::TopRight | Self::BottomRight) {
1920.0 - dx - width
} else {
dx
},
y: if matches!(self, Self::BottomLeft | Self::BottomRight) {
1080.0 - dy - height
} else {
dy
},
width,
height,
}
.validate()
}
}
/// Two-layer document with one undo record per complete gesture/edit.
pub struct Layout {
layers: [Geometry; 2],
selected: Option<usize>,
undo: Vec<[Geometry; 2]>,
redo: Vec<[Geometry; 2]>,
drag: Option<(usize, [Geometry; 2], [f64; 2])>,
}
impl Default for Layout {
fn default() -> Self {
Self {
layers: [
Geometry {
x: 120.0,
y: 180.0,
width: 640.0,
height: 360.0,
},
Geometry {
x: 1160.0,
y: 180.0,
width: 640.0,
height: 360.0,
},
],
selected: Some(1),
undo: Vec::new(),
redo: Vec::new(),
drag: None,
}
}
}
impl Layout {
pub fn layers(&self) -> &[Geometry; 2] {
&self.layers
}
pub fn selected(&self) -> Option<usize> {
self.selected
}
pub fn select(&mut self, index: Option<usize>) {
self.finish_drag();
self.selected = index.filter(|i| *i < 2);
}
pub fn hit(&self, point: [f64; 2]) -> Option<usize> {
(0..2).rev().find(|i| self.layers[*i].contains(point))
}
fn remember(&mut self, before: [Geometry; 2]) {
if before != self.layers {
if self.undo.len() == 100 {
self.undo.remove(0);
}
self.undo.push(before);
self.redo.clear();
}
}
pub fn apply(&mut self, index: usize, geometry: Geometry) -> Result<(), String> {
let geometry = geometry.validate()?;
if index >= 2 {
return Err("Select an existing layer.".into());
}
self.finish_drag();
let before = self.layers;
self.layers[index] = geometry;
self.remember(before);
Ok(())
}
pub fn nudge(&mut self, dx: f64, dy: f64) -> Result<(), String> {
if let Some(i) = self.selected {
let g = self.layers[i];
self.apply(
i,
Geometry {
x: g.x + dx,
y: g.y + dy,
..g
},
)?;
}
Ok(())
}
pub fn start_drag(&mut self, point: [f64; 2]) {
self.finish_drag();
self.selected = self.hit(point);
if let Some(i) = self.selected {
self.drag = Some((i, self.layers, point));
}
}
pub fn drag_to(&mut self, point: [f64; 2]) {
if let Some((i, before, start)) = self.drag {
let g = before[i];
let next = Geometry {
x: g.x + (point[0] - start[0]).round(),
y: g.y + (point[1] - start[1]).round(),
..g
};
if next.validate().is_ok() {
self.layers[i] = next;
}
}
}
pub fn dragging(&self) -> bool {
self.drag.is_some()
}
pub fn finish_drag(&mut self) {
if let Some((_, before, _)) = self.drag.take() {
self.remember(before);
}
}
pub fn cancel_drag(&mut self) {
if let Some((_, before, _)) = self.drag.take() {
self.layers = before;
}
}
pub fn undo(&mut self) {
self.finish_drag();
if let Some(before) = self.undo.pop() {
self.redo.push(self.layers);
self.layers = before;
}
}
pub fn redo(&mut self) {
self.finish_drag();
if let Some(after) = self.redo.pop() {
self.undo.push(self.layers);
self.layers = after;
}
}
}
#[derive(Clone, Debug)]
pub struct DrawioShape {
pub id: String,
pub geometry: Geometry,
}
/// Read raw or once-percent-encoded mxGraphModel XML. Values map 1:1 to pixels.
/// Nested, relative, rotated and nonrectangular geometry is intentionally refused.
pub fn parse_drawio(input: &str) -> Result<Vec<DrawioShape>, String> {
if input.len() > 1_048_576 {
return Err("Clipboard text exceeds 1 MiB.".into());
}
let input = input.trim();
let decoded;
let xml = if input.starts_with('<') {
input
} else {
decoded = decode_percent(input)?;
decoded.trim()
};
let doc = roxmltree::Document::parse(xml).map_err(|e| format!("Invalid draw.io XML: {e}"))?;
let model = doc.root_element();
if !model.has_tag_name("mxGraphModel") {
return Err("Paste draw.io mxGraphModel XML, not a compressed file or an image.".into());
}
let root = model
.children()
.find(|n| n.has_tag_name("root"))
.ok_or("draw.io root is missing.")?;
let mut cells = HashMap::new();
for n in root.children().filter(|n| n.is_element()) {
if !n.has_tag_name("mxCell") {
return Err("Wrapped objects are not supported yet. Copy plain rectangles.".into());
}
let id = n.attribute("id").ok_or("A cell has no ID.")?;
if cells.insert(id, n).is_some() {
return Err("Duplicate draw.io cell ID.".into());
}
}
let mut result = Vec::new();
for cell in root.children().filter(|n| n.has_tag_name("mxCell")) {
if cell.attribute("edge") == Some("1") {
return Err("Connections are not supported. Copy rectangles only.".into());
}
if cell.attribute("vertex") != Some("1") {
continue;
}
let id = cell.attribute("id").unwrap();
let parent = cell
.attribute("parent")
.and_then(|p| cells.get(p))
.ok_or("Missing parent; grouped/partial geometry is unsupported.")?;
let is_layer = parent.attribute("vertex").is_none()
&& parent
.attribute("parent")
.and_then(|p| cells.get(p))
.is_some_and(|p| {
p.attribute("parent").is_none() && p.attribute("vertex").is_none()
});
if !is_layer {
return Err(
"Grouped or nested rectangles are not supported yet. Ungroup before copying."
.into(),
);
}
for entry in cell
.attribute("style")
.unwrap_or("")
.split(';')
.filter(|s| !s.is_empty())
{
let (key, value) = entry
.split_once('=')
.ok_or("Named/inherited draw.io styles are unsupported.")?;
if (key == "shape" && value != "rectangle")
|| (matches!(key, "rotation" | "flipH" | "flipV") && value != "0")
{
return Err("Only unrotated rectangles are supported; remove shape transforms before copying.".into());
}
}
let geometries: Vec<_> = cell.children().filter(|n| n.is_element()).collect();
if geometries.len() != 1 || !geometries[0].has_tag_name("mxGeometry") {
return Err("Expected one plain geometry per rectangle.".into());
}
let g = geometries[0];
if g.attribute("relative").is_some_and(|v| v != "0") || g.children().any(|n| n.is_element())
{
return Err("Relative, offset or alternate bounds are not supported yet.".into());
}
let number = |name, default| -> Result<f64, String> {
g.attribute(name)
.or(default)
.ok_or_else(|| format!("Missing {name}."))?
.parse()
.map_err(|_| format!("Invalid {name}."))
};
let geometry = Geometry {
x: number("x", Some("0"))?,
y: number("y", Some("0"))?,
width: number("width", None)?,
height: number("height", None)?,
}
.validate()?;
result.push(DrawioShape {
id: id.to_owned(),
geometry,
});
}
if result.is_empty() {
return Err("No rectangles found in the draw.io clipboard.".into());
}
Ok(result)
}
fn decode_percent(input: &str) -> Result<String, String> {
let mut out = Vec::with_capacity(input.len());
let mut bytes = input.bytes();
while let Some(b) = bytes.next() {
if b == b'%' {
let hex = |c: u8| (c as char).to_digit(16).map(|v| v as u8);
let a = bytes
.next()
.and_then(hex)
.ok_or("Invalid percent escape in clipboard.")?;
let b = bytes
.next()
.and_then(hex)
.ok_or("Invalid percent escape in clipboard.")?;
out.push(a * 16 + b);
} else {
out.push(b);
} // '+' is literal in encodeURIComponent, not a space.
}
String::from_utf8(out).map_err(|_| "Clipboard is not valid UTF-8.".into())
}

View File

@ -1,4 +1,4 @@
//! Appearance-only desktop study. All geometry and controls are illustrative.
//! Native offline layer positioning workspace.
use eframe::egui::{self, Align2, Color32, FontId, Pos2, Rect, Stroke, StrokeKind, Vec2};
const BG: Color32 = Color32::from_rgb(17, 23, 32);
@ -13,7 +13,7 @@ const PURPLE: Color32 = Color32::from_rgb(102, 85, 217);
fn main() -> eframe::Result {
eframe::run_native(
"Midra Layout · Appearance preview",
"Midra Layout",
eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([1440.0, 940.0])
@ -21,13 +21,20 @@ fn main() -> eframe::Result {
..Default::default()
},
Box::new(|cc| {
cc.egui_ctx.set_visuals(egui::Visuals::dark());
Ok(Box::new(Appearance))
let mut style = (*cc.egui_ctx.style()).clone();
style.visuals = egui::Visuals::dark();
style.visuals.extreme_bg_color = FIELD;
style.visuals.selection.bg_fill = PURPLE;
style.visuals.widgets.inactive.bg_fill = FIELD;
style.visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, LINE);
style.spacing.item_spacing = Vec2::new(12.0, 10.0);
cc.egui_ctx.set_style(style);
Ok(Box::new(gui::Editor::default()))
}),
)
}
struct Appearance;
mod gui;
/// Draw in local logical points; viewport artwork alone uses a fitted scale.
struct Ink {
@ -89,11 +96,6 @@ impl Ink {
self.text(x + 12.0, y + 9.0, label, 13.0, TEXT);
}
fn chevron(&self, x: f32, y: f32) {
self.line([x, y], [x + 4.0, y + 4.0], MUTED);
self.line([x + 4.0, y + 4.0], [x + 8.0, y], MUTED);
}
fn field(&self, x: f32, y: f32, w: f32, label: &str, value: &str) {
self.text(x, y, label, 12.0, MUTED);
self.card(x, y + 23.0, w, 42.0, FIELD, LINE);
@ -101,168 +103,6 @@ impl Ink {
}
}
impl eframe::App for Appearance {
fn update(&mut self, ctx: &egui::Context, _: &mut eframe::Frame) {
egui::TopBottomPanel::top("header")
.exact_height(64.0)
.frame(egui::Frame::NONE.fill(PANEL))
.show(ctx, |ui| {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
ink.text(24.0, 21.0, "MIDRA / LAYOUT", 21.0, TEXT);
ink.line([218.0, 22.0], [218.0, 43.0], LINE);
ink.text(238.0, 26.0, "Offline position helper", 13.0, MUTED);
ink.text(r.width() - 347.0, 27.0, "EIKOS 4K", 12.0, CYAN);
ink.button(r.width() - 212.0, 15.0, 188.0, "Copy coordinates", false);
ink.line([0.0, 63.0], [r.width(), 63.0], LINE);
});
egui::TopBottomPanel::bottom("status")
.exact_height(34.0)
.frame(egui::Frame::NONE.fill(PANEL))
.show(ctx, |ui| {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
ink.painter.circle_filled(ink.point(24.0, 17.0), 3.0, CYAN);
ink.text(36.0, 10.0, "OFFLINE", 11.0, MUTED);
ink.text(
116.0,
10.0,
"Appearance preview · controls inactive",
12.0,
MUTED,
);
ink.text(
r.width() - 278.0,
10.0,
"Screen pixels / 1920 × 1080",
12.0,
MUTED,
);
});
egui::SidePanel::right("inspector")
.exact_width(392.0)
.resizable(false)
.frame(egui::Frame::NONE.fill(PANEL).inner_margin(24.0))
.show(ctx, |ui| {
egui::ScrollArea::vertical().show(ui, |ui| {
let (r, _) = ui.allocate_exact_size(
Vec2::new(ui.available_width(), 814.0),
egui::Sense::hover(),
);
inspector(&Ink::new(ui, r), r.width());
});
});
egui::CentralPanel::default()
.frame(egui::Frame::NONE.fill(BG))
.show(ctx, workspace);
}
}
fn inspector(ink: &Ink, w: f32) {
ink.text(0.0, 2.0, "LAYERS", 11.0, MUTED);
for (y, label, color, selected) in [
(28.0, "01 Presenter", AMBER, false),
(72.0, "02 Slides", CYAN, true),
] {
ink.card(0.0, y, w, 38.0, FIELD, if selected { CYAN } else { LINE });
ink.text(13.0, y + 10.0, label, 15.0, color);
ink.text(w - 59.0, y + 12.0, "Visible", 11.0, MUTED);
}
ink.line([0.0, 130.0], [w, 130.0], LINE);
ink.text(0.0, 150.0, "02 / Slides", 25.0, TEXT);
ink.text(0.0, 186.0, "Source format", 12.0, MUTED);
ink.card(0.0, 209.0, w, 34.0, FIELD, LINE);
ink.text(12.0, 218.0, "16:9 / 1920 × 1080", 13.0, TEXT);
ink.chevron(w - 24.0, 224.0);
ink.text(0.0, 264.0, "POSITION FROM SCREEN CORNER", 11.0, MUTED);
ink.card(0.0, 289.0, 94.0, 58.0, FIELD, LINE);
for (x, y) in [(9.0, 298.0), (85.0, 298.0), (9.0, 338.0), (85.0, 338.0)] {
ink.rect(
x - 3.0,
y - 3.0,
6.0,
6.0,
if x == 85.0 && y == 298.0 { CYAN } else { MUTED },
);
}
ink.text(112.0, 296.0, "Top right", 18.0, TEXT);
ink.text(112.0, 323.0, "Offsets inward", 12.0, MUTED);
let half = (w - 12.0) / 2.0;
ink.field(0.0, 367.0, half, "From right", "120 px");
ink.field(half + 12.0, 367.0, half, "From top", "180 px");
ink.field(0.0, 449.0, half, "Layer width", "640 px");
ink.field(half + 12.0, 449.0, half, "Layer height", "360 px");
ink.text(
0.0,
531.0,
"Changing corner keeps the layer in place.",
12.0,
MUTED,
);
ink.line([0.0, 559.0], [w, 559.0], LINE);
ink.text(0.0, 580.0, "WEBRCS / CENTER POSITION", 11.0, CYAN);
ink.field(0.0, 610.0, half, "Horizontal · from left", "1480 px");
ink.field(half + 12.0, 610.0, half, "Vertical · from top", "360 px");
ink.text(0.0, 690.0, "Size 640 × 360 px", 13.0, MUTED);
ink.button(0.0, 720.0, w, "Copy position values", true);
ink.text(0.0, 776.0, "Paste geometry…", 14.0, TEXT);
ink.text(
0.0,
799.0,
"Preview coordinates before applying.",
12.0,
MUTED,
);
}
fn workspace(ui: &mut egui::Ui) {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
ink.button(24.0, 20.0, 185.0, "Screen 1 · Full HD", false);
ink.button(221.0, 20.0, 149.0, "Reference image", false);
ink.button(382.0, 20.0, 103.0, "Snap: off", false);
ink.button(24.0, 67.0, 103.0, "Fit screen", false);
ink.button(139.0, 67.0, 91.0, "Zoom", false);
ink.chevron(208.0, 82.0);
ink.text(25.0, 132.0, "YOUR SCREEN, PRECISELY PLACED", 12.0, CYAN);
ink.text(25.0, 157.0, "Two layers. One clear view.", 17.0, MUTED);
// Camera fit for this appearance study only; no editable layer geometry.
let scale = ((r.width() - 88.0) / 960.0).min((r.height() - 300.0) / 540.0);
let size = Vec2::new(960.0, 540.0) * scale;
let origin = r.min
+ Vec2::new(
(r.width() - size.x) / 2.0,
222.0 + (r.height() - 300.0 - size.y) / 2.0,
);
let screen = Ink {
painter: ui.painter_at(r),
origin,
scale,
};
screen_artwork(&screen);
ink.text(
24.0,
r.height() - 57.0,
"Reference: stage-layout.png · 1920 × 1080 · Locked",
12.0,
MUTED,
);
ink.text(
24.0,
r.height() - 31.0,
"Illustrative artwork and values · no files loaded",
12.0,
MUTED,
);
}
fn screen_artwork(ink: &Ink) {
ink.text(0.0, -29.0, "SCREEN 1", 12.0, MUTED);
ink.text(790.0, -29.0, "1920 × 1080 px", 13.0, MUTED);
@ -291,31 +131,4 @@ fn screen_artwork(ink: &Ink) {
12.0,
MUTED,
);
for (x, color, label, selected) in [
(60.0, AMBER, "01 / PRESENTER", false),
(580.0, CYAN, "02 / SLIDES", true),
] {
ink.rect(x, 90.0, 320.0, 180.0, Color32::from_rgb(23, 59, 80));
ink.painter.rect_stroke(
Rect::from_min_size(ink.point(x, 90.0), Vec2::new(320.0, 180.0) * ink.scale),
0.0,
Stroke::new(1.0_f32, color),
StrokeKind::Inside,
);
ink.text(x + 15.0, 107.0, label, 15.0, color);
ink.text(x + 15.0, 242.0, "640 × 360 px", 14.0, TEXT);
if selected {
for (dx, dy) in [(0.0, 0.0), (320.0, 0.0), (0.0, 180.0), (320.0, 180.0)] {
ink.card(x + dx - 4.0, 86.0 + dy, 8.0, 8.0, PANEL, CYAN);
}
ink.line([x + 152.0, 180.0], [x + 168.0, 180.0], CYAN);
ink.line([x + 160.0, 172.0], [x + 160.0, 188.0], CYAN);
}
}
ink.line([916.0, 0.0], [916.0, 90.0], CYAN);
ink.line([910.0, 0.0], [922.0, 0.0], CYAN);
ink.line([910.0, 90.0], [922.0, 90.0], CYAN);
ink.text(923.0, 40.0, "180", 12.0, CYAN);
ink.line([900.0, 288.0], [960.0, 288.0], CYAN);
ink.text(900.0, 302.0, "120 px", 12.0, CYAN);
}

View File

@ -0,0 +1 @@
%3CmxGraphModel%3E%3Croot%3E%3CmxCell%20id%3D%220%22%2F%3E%3CmxCell%20id%3D%221%22%20parent%3D%220%22%2F%3E%3CmxCell%20id%3D%222%22%20parent%3D%221%22%20style%3D%22rounded%3D0%3BwhiteSpace%3Dwrap%3Bhtml%3D1%3Baspect%3Dfixed%3BfillColor%3Dnone%3BstrokeWidth%3D5%3BstrokeColor%3Dlight-dark(%23000000%2C%2366FF66)%3B%22%20value%3D%22%22%20vertex%3D%221%22%3E%3CmxGeometry%20height%3D%22531.58%22%20width%3D%22945%22%20x%3D%2212%22%20y%3D%22271%22%20as%3D%22geometry%22%2F%3E%3C%2FmxCell%3E%3C%2Froot%3E%3C%2FmxGraphModel%3E

View File

@ -0,0 +1,244 @@
use midra_layout::{Corner, Geometry, Layout, parse_drawio};
const SAMPLE: &str = include_str!("fixtures/drawio-rectangle.txt");
fn xml(body: &str) -> String {
format!(
r#"<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/>{body}</root></mxGraphModel>"#
)
}
fn vertex(geometry: &str, style: &str) -> String {
xml(&format!(
r#"<mxCell id="2" parent="1" vertex="1" style="{style}">{geometry}</mxCell>"#
))
}
fn g() -> Geometry {
Geometry {
x: 12.0,
y: 271.0,
width: 945.0,
height: 531.58,
}
}
#[test]
fn supplied_clipboard_preserves_decimals_and_converts_center() {
let shapes = parse_drawio(SAMPLE).unwrap();
assert_eq!(shapes.len(), 1);
assert_eq!(shapes[0].id, "2");
assert_eq!(shapes[0].geometry, g());
assert_eq!(shapes[0].geometry.center(), [484.5, 536.79]);
assert!((g().width / g().height - 16.0 / 9.0).abs() > 0.000001); // no preset snapping
}
#[test]
fn raw_xml_defaults_missing_origin_and_keeps_negative_and_fractional_coordinates() {
let raw = vertex(r#"<mxGeometry width="20.5" height="30"/>"#, "rounded=0;");
let a = parse_drawio(&raw).unwrap()[0].geometry;
assert_eq!([a.x, a.y], [0.0, 0.0]);
let raw = vertex(
r#"<mxGeometry x="-12.25" y="2.5" width="20.5" height="30"/>"#,
"",
);
let a = parse_drawio(&raw).unwrap()[0].geometry;
assert_eq!([a.x, a.y], [-12.25, 2.5]);
}
#[test]
fn multiple_rectangles_keep_source_order() {
let data = xml(
r#"<mxCell id="9" vertex="1" parent="1"><mxGeometry width="50" height="30"/></mxCell><mxCell id="2" vertex="1" parent="1"><mxGeometry x="100" width="10" height="10"/></mxCell>"#,
);
let list = parse_drawio(&data).unwrap();
assert_eq!(
list.iter().map(|s| s.id.as_str()).collect::<Vec<_>>(),
vec!["9", "2"]
);
}
#[test]
fn invalid_clipboard_is_rejected_without_panicking() {
for s in [
"",
"%",
"%3",
"%GG",
"%ff",
"not geometry",
"<mxGraphModel>",
"<mxfile/>",
"<mxGraphModel/>",
"<mxGraphModel><root/></mxGraphModel>",
] {
assert!(parse_drawio(s).is_err(), "{s}");
}
assert!(parse_drawio(&"x".repeat(1_048_577)).is_err());
assert!(
parse_drawio(
r#"<!DOCTYPE a [<!ENTITY e "hello">]><mxGraphModel><root>&e;</root></mxGraphModel>"#
)
.is_err()
);
}
#[test]
fn invalid_sizes_or_nonfinite_numbers_cannot_enter_document() {
for attr in [
r#"width="0" height="2""#,
r#"width="-1" height="2""#,
r#"width="NaN" height="2""#,
r#"width="2" height="inf""#,
r#"x="1e300" width="2" height="2""#,
r#"height="20""#,
] {
assert!(parse_drawio(&vertex(&format!("<mxGeometry {attr}/>"), "")).is_err());
}
let mut layout = Layout::default();
let before = *layout.layers();
assert!(
layout
.apply(
1,
Geometry {
width: f64::NAN,
..g()
}
)
.is_err()
);
assert_eq!(*layout.layers(), before);
assert!(layout.apply(7, g()).is_err());
assert_eq!(*layout.layers(), before);
}
#[test]
fn transforms_groups_connections_and_ambiguous_geometry_are_refused() {
for style in [
"rotation=90;",
"flipH=1;",
"shape=ellipse;",
"ellipse;",
"group;",
] {
assert!(parse_drawio(&vertex(r#"<mxGeometry width="10" height="10"/>"#, style)).is_err());
}
for geometry in [
r#"<mxGeometry relative="1" width="10" height="10"/>"#,
r#"<mxGeometry width="10" height="10"><mxPoint x="2" as="offset"/></mxGeometry>"#,
r#"<mxGeometry width="10" height="10"/><mxGeometry width="20" height="20"/>"#,
] {
assert!(parse_drawio(&vertex(geometry, "")).is_err());
}
for body in [
r#"<mxCell id="2" parent="1" edge="1"/>"#,
r#"<object><mxCell id="2"/></object>"#,
r#"<mxCell id="1"/>"#,
r#"<mxCell id="2" parent="missing" vertex="1"><mxGeometry width="10" height="10"/></mxCell>"#,
r#"<mxCell id="2" parent="1" vertex="1"><mxGeometry width="10" height="10"/></mxCell><mxCell id="3" parent="2" vertex="1"><mxGeometry width="5" height="5"/></mxCell>"#,
] {
assert!(parse_drawio(&xml(body)).is_err());
}
}
#[test]
fn percent_decoding_is_once_and_does_not_treat_plus_as_space() {
let raw = vertex(r#"<mxGeometry x="+12" width="10" height="10"/>"#, "");
let encoded = raw.replace('<', "%3C").replace('>', "%3E");
assert_eq!(parse_drawio(&encoded).unwrap()[0].geometry.x, 12.0);
assert!(parse_drawio(&encoded.replace('%', "%25")).is_err());
}
#[test]
fn corners_roundtrip_without_moving_or_rounding_the_box() {
for c in [
Corner::TopLeft,
Corner::TopRight,
Corner::BottomLeft,
Corner::BottomRight,
] {
let [x, y] = c.offsets(g());
let result = c.geometry(x, y, g().width, g().height).unwrap();
assert!((result.x - g().x).abs() < 1e-10);
assert!((result.y - g().y).abs() < 1e-10);
assert_eq!(result.width, g().width);
}
let a = Corner::TopRight
.geometry(120.0, 180.0, 640.0, 360.0)
.unwrap();
assert_eq!(a.center(), [1480.0, 360.0]);
}
#[test]
fn paste_and_undo_change_only_the_target() {
let mut l = Layout::default();
let original = *l.layers();
l.apply(1, parse_drawio(SAMPLE).unwrap()[0].geometry)
.unwrap();
assert_eq!(l.layers()[0], original[0]);
assert_eq!(l.layers()[1], g());
l.undo();
assert_eq!(*l.layers(), original);
l.redo();
assert_eq!(l.layers()[1], g());
l.undo();
l.nudge(1.0, 0.0).unwrap();
let nudged = *l.layers();
l.redo();
assert_eq!(*l.layers(), nudged);
}
#[test]
fn drag_uses_original_position_and_is_one_undo_record() {
let mut l = Layout::default();
l.apply(1, g()).unwrap();
let original = *l.layers();
l.start_drag([20.0, 280.0]);
for n in 1..10 {
l.drag_to([20.0 + n as f64, 280.0 + n as f64]);
}
l.finish_drag();
assert_eq!(
l.layers()[1],
Geometry {
x: 21.0,
y: 280.0,
..g()
}
);
l.undo();
assert_eq!(*l.layers(), original);
l.redo();
assert_eq!(l.layers()[1].x, 21.0);
}
#[test]
fn cancel_drag_restores_geometry_and_retains_fractional_origin() {
let mut l = Layout::default();
l.apply(1, Geometry { x: 12.25, ..g() }).unwrap();
let original = *l.layers();
l.start_drag([20.0, 280.0]);
l.drag_to([22.8, 282.2]);
assert_eq!(l.layers()[1].x, 15.25);
l.cancel_drag();
assert_eq!(*l.layers(), original);
assert!(!l.dragging());
}
#[test]
fn hit_testing_matches_stacking_and_background_deselects() {
let mut l = Layout::default();
l.apply(0, g()).unwrap();
l.apply(1, g()).unwrap();
assert_eq!(l.hit([20.0, 280.0]), Some(1));
l.start_drag([-100.0, -100.0]);
assert_eq!(l.selected(), None);
l.nudge(10.0, 10.0).unwrap();
assert_eq!(l.layers()[0], g());
l.select(Some(77));
assert_eq!(l.selected(), None);
}
#[test]
fn offscreen_placement_is_preserved_and_nudging_keeps_size() {
let mut l = Layout::default();
l.apply(
1,
Geometry {
x: -20.25,
y: 1200.0,
..g()
},
)
.unwrap();
l.nudge(1.0, -10.0).unwrap();
let a = l.layers()[1];
assert_eq!(a.x, -19.25);
assert_eq!(a.y, 1190.0);
assert_eq!(a.width, 945.0);
assert!(a.outside());
}

View File

@ -1,9 +1,12 @@
# Midra layout helper: plan and visual proposals
Status: a [Rust/egui appearance preview](midra-layout.md) is available. Its controls
and sample values are illustrative; positioning, crop logic, device connection
and REST calls are not implemented. The implementation checklist below remains
open until those behaviors and acceptance gates are complete.
Status: the [Rust/egui positioning draft](midra-layout.md) supports draw.io
geometry paste with review, two-layer selection and movement, numeric corner
positioning/size, undo/redo and camera zoom/pan. Concept A is user-approved.
Reference artwork remains illustrative; output is fixed to 1920 × 1080.
Custom resolution, source/input formats, image import, multi-selection alignment,
cropping, device connection and REST calls are not implemented. Checklist gates
that combine implemented and outstanding work remain open.
Target: Analog Way Eikos 4K, running the latest firmware according to the user.
Record the actual installed version during compatibility checks; do not infer it
from a different Midra generation's documentation. Working name: **Midra Layout**.
@ -56,7 +59,7 @@ label as WebRCS-compatible. The example math below is provisional until then.
### 2. Review visual direction and prove the viewport
- [ ] Choose a direction from the three proposals below. Recommended: A, with
- [x] Choose a direction from the three proposals below. Approved: A, with
B's optional rulers and C's contextual alignment panel later.
- [ ] Build a disposable viewport interaction spike with two rectangles before
committing to the full UI. Rust/egui is the preferred starting point because
@ -73,8 +76,8 @@ toolkit cannot meet these needs, resolve that before building the rest.
### 3. Implement geometry independently of the UI
- [ ] Add the future workspace member `crates/midra-layout/` with shared geometry
and a desktop binary. Do not add placeholder workspace members during planning.
- [x] Add workspace member `crates/midra-layout/` with shared geometry
and a desktop binary.
- [ ] Model screen dimensions and stable layer IDs with canonical top-left
position and final visible size. Keep selection, camera and reference image separate.
- [ ] Define source format/native dimensions, input crop, advanced crop and
@ -160,8 +163,9 @@ layer; changing image opacity, visibility, zoom or filtering changes no geometry
- [ ] Treat Ctrl/Cmd-V in a focused text input as normal text paste. Elsewhere,
open geometry preview; do not mutate the document merely by reading clipboard.
- [ ] Define adapters by source format/version. Collect actual clipboard samples
from the first requested software before claiming support; that software is
not yet specified. Do not guess an application from an unlabeled number tuple.
from each requested software before claiming support. The first adapter now
supports the supplied draw.io mxGraphModel clipboard example. Do not guess an
application from an unlabeled number tuple.
- [ ] Make points, inches, percentages, source canvas origins, decimal conventions
and scale explicit. Ambiguity produces an explanation, not a guessed placement.
- [ ] Validate the complete proposed edit before applying it atomically, with one
@ -340,6 +344,6 @@ offline simulator that may help verify behavior without connecting this helper
to hardware. Simulator agreement should still be checked against the installed
WebRCS version.
Open decisions before implementation: preferred visual direction; exact installed
firmware; first clipboard source application and representative payload; primary
operator OS/display scale. None prevents reviewing these design proposals.
Open compatibility decisions: exact installed firmware and primary operator
OS/display scale. Concept A is approved and draw.io is the first clipboard source,
with the user-supplied percent-encoded rectangle retained as a regression fixture.

View File

@ -1,29 +1,97 @@
# Midra Layout appearance preview
# Midra Layout
A native Rust/egui visual draft of Concept A: dark operator workspace, fitted
screen artwork, two sample layers, selection markers, dimension guides and a
right-hand inspector. The inspector includes source format, corner offsets,
layer dimensions and illustrative WebRCS values.
Run from the repository root:
A native Rust/egui workspace for positioning two rectangular layers offline.
Select layers, paste draw.io geometry, move them visually or enter exact corner
positions and dimensions. Center coordinates update for manual transfer to WebRCS.
No device connection or REST calls are made.
```sh
cargo run --locked -p midra-layout
```
This is **appearance only**. Buttons, fields, layer selection, copy/paste,
zoom and movement are inactive. The screen artwork is drawn into the preview;
`stage-layout.png` is an illustrative label, not a loaded file. All displayed
coordinates are fixed sample values, not computed device settings. There is no
device connection, file import, clipboard access or persistent configuration.
## Paste from draw.io
The window can be resized; the screen retains its aspect ratio and the right
inspector scrolls on shorter windows. The minimum window size is 1000 × 720
logical points. Native desktop launch requires a graphical session.
1. Select the target layer on the canvas or in the right-hand list.
2. Copy an ungrouped rectangle in draw.io, then press **Ctrl/Cmd-V** with the
viewport focused. Alternatively, click **Paste draw.io…**, paste into the text
area and click **Read geometry**.
3. Review the target layer, before/after position and size. If multiple rectangles
were copied, choose one explicitly; the importer does not guess a mapping to
the two layers.
4. Leave **Include size / format** checked to import width and height along with
position, or uncheck it for position only. Click **Apply to selected target**.
The crate is a Cargo workspace member, so existing workspace lint, tests, docs
and coverage commands include it. It has no positioning/cropping logic to test
yet; visual review is the relevant acceptance check for this draft.
The first adapter accepts raw or once-percent-encoded `mxGraphModel` XML, like
[the supplied clipboard fixture](../crates/midra-layout/tests/fixtures/drawio-rectangle.txt).
Draw.io coordinates map **1:1 to screen pixels**, with a top-left origin. This is
an explicit import convention; no page-scale, physical-unit or viewport-size
conversion is inferred. Missing X/Y means zero. Decimal dimensions are preserved.
See the [project plan and SVG concepts](midra-layout-plan.md) and
The supplied example imports **X 12, Y 271, width 945, height 531.58**. The center
is **484.5, 536.79**. The visible box has its exact imported ratio; it is not rounded
or coerced into a 16:9 preset. “Format” here means the visible rectangle's width,
height and aspect, not native source format or advanced cropping.
The adapter ignores colors, stroke width, text, style aspect locks and other
appearance settings. It currently rejects grouped/nested geometry, connections,
nonrectangular shapes, relative coordinates, alternate bounds, rotated/flipped
objects, named/inherited styles, wrapped objects and compressed `.drawio` files.
Mixed selections containing unsupported objects are rejected as a whole. Invalid
input makes no document changes. Text is limited to 1 MiB; geometry must have
finite coordinates within ±1,000,000 px and positive sizes up to 1,000,000 px.
These are application limits, not verified Eikos limits.
Draw.io also exposes raw page XML through **Extras → Edit Diagram**, as described
in its [source-editing documentation](https://www.drawio.com/docs/manual/advanced/diagram-source-edit/).
Support is based on the supplied clipboard data and regression fixtures; live
clipboard testing against a running draw.io instance remains to be done.
## Move and edit layers
- Click a layer or its list entry to select it. In overlaps, the upper layer wins;
the list lets you reach the lower layer. Clicking empty canvas clears selection.
- Drag to move. Movement uses whole-screen-pixel deltas and preserves any fractional
starting position and dimensions. Selection handles currently indicate bounds;
resizing uses the numeric width/height fields.
- Arrow keys move by **1 px**; Shift-arrow moves by **10 px**.
- Choose one of the four corner markers. Switching corner changes the displayed
offsets without moving the layer. Enter offsets, width and height, then click
**Apply position / size** or press Enter in a field. Resizing preserves that
corner's offsets. Invalid values leave the document unchanged.
- **Escape** cancels a drag or restores uncommitted numeric fields. In the paste
dialog it closes the preview without applying it.
- **Undo/Redo** buttons or Ctrl/Cmd-Z, Ctrl/Cmd-Shift-Z (also Ctrl/Cmd-Y) reverse
edits. Each drag, applied paste or numeric edit is one step; retain 100 undo
records. View changes and selection are not document edits.
- Scroll over the viewport to zoom around the pointer. Space-drag or middle-drag
pans. **Fit screen** resets the view; **Fit layer** frames the selected layer.
Camera changes do not modify coordinates. Off-screen layers retain their exact
coordinates, display a warning and remain selectable through the layer list.
- **Copy position values** copies labeled plain text with center position and
dimensions. This is not a native WebRCS clipboard payload.
Text inputs receive normal text paste and arrow navigation while focused; they
never interpret these actions as geometry import or layer movement. Paste preview
identifies its target explicitly and changes only that layer.
## Current limits
The screen is currently fixed to **1920 × 1080**, with two live rectangles.
Reference artwork is illustrative, not a loaded image or live video. Source/input
formats, custom output resolution, image import, cropping, alignment and persistent
session files are future work. Sessions currently live only in memory.
The displayed WebRCS values use the planned center-from-top-left convention.
Actual firmware coordinate limits, crop behavior and decimal acceptance are not
verified yet. Fractional values remain visible rather than silently rounded.
The window can be resized; the screen keeps its aspect ratio, and the right
inspector scrolls on shorter windows. Minimum size is 1000 × 720 logical points.
A graphical desktop session is required to launch.
The Cargo workspace includes this crate in lint, tests, docs and coverage.
Regression tests cover the supplied clipboard, malformed/unsupported input,
corner conversion, drag/undo, selection, and GUI paste/focus behavior.
See the [project plan](midra-layout-plan.md) and
[resolution/cropping specification](midra-layout-resolutions.md) for future work.