Add multi-layer selection and explicit alignment targets

This commit is contained in:
Dandaedre 2026-11-13 12:04:57 +01:00
parent 6a45ddf155
commit 38a0179d2f
5 changed files with 762 additions and 92 deletions

View File

@ -1,5 +1,5 @@
use super::*;
use midra_layout::{Corner, DrawioShape, Geometry, Layout, parse_drawio};
use midra_layout::{AlignTarget, Alignment, Corner, DrawioShape, Geometry, Layout, parse_drawio};
pub struct Editor {
layout: Layout,
@ -10,6 +10,15 @@ pub struct Editor {
zoom: f32,
pan: Vec2,
panning: bool,
marquee: Option<Marquee>,
align_target: AlignTarget,
}
#[derive(Clone, Copy)]
struct Marquee {
start: [f64; 2],
end: [f64; 2],
base: [bool; 2],
previous: [bool; 2],
}
struct Paste {
target: usize,
@ -46,6 +55,8 @@ impl Default for Editor {
zoom: 1.0,
pan: Vec2::ZERO,
panning: false,
marquee: None,
align_target: AlignTarget::Selection,
};
this.sync();
this
@ -95,7 +106,7 @@ impl Editor {
}
self.paste = Some(p);
} else {
self.error = "Select a layer before pasting.".into();
self.error = "Select exactly one layer before pasting.".into();
}
}
fn apply_fields(&mut self) {
@ -120,17 +131,25 @@ impl Editor {
}
}
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)
));
let entries: Vec<_> = self
.layout
.selected_indices()
.into_iter()
.map(|i| {
let g = self.layout.layers()[i];
let [h, v] = g.center();
format!(
"{}\nHorizontal: {} px\nVertical: {} px\nWidth: {} px\nHeight: {} px",
label(i),
number(h),
number(v),
number(g.width),
number(g.height)
)
})
.collect();
if !entries.is_empty() {
ctx.copy_text(entries.join("\n\n"));
}
}
fn shortcuts(&mut self, ctx: &egui::Context) {
@ -139,6 +158,9 @@ impl Editor {
}
if ctx.input(|i| i.key_pressed(egui::Key::Escape)) {
self.layout.cancel_drag();
if let Some(m) = self.marquee.take() {
self.layout.set_selection(m.previous);
}
self.sync();
ctx.memory_mut(|m| {
if let Some(id) = m.focused() {
@ -166,7 +188,7 @@ impl Editor {
self.open_paste(text);
return;
}
if self.layout.dragging() {
if self.layout.dragging() || self.marquee.is_some() || self.panning {
return;
}
let command = ctx.input(|i| i.modifiers.command);
@ -313,7 +335,7 @@ impl Editor {
}
fn inspector(&mut self, ui: &mut egui::Ui) {
let (r, _) =
ui.allocate_exact_size(Vec2::new(ui.available_width(), 920.0), egui::Sense::hover());
ui.allocate_exact_size(Vec2::new(ui.available_width(), 960.0), egui::Sense::hover());
let ink = Ink::new(ui, r);
let w = r.width();
ink.text(0.0, 2.0, "LAYERS", 11.0, MUTED);
@ -326,7 +348,7 @@ impl Editor {
w,
38.0,
FIELD,
if self.layout.selected() == Some(i) {
if self.layout.selection_mask()[i] {
color
} else {
LINE
@ -334,13 +356,34 @@ impl Editor {
);
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));
if click_shift_modifier(ui) {
self.layout.toggle(i);
} else {
self.layout.select(Some(i));
}
self.sync();
}
}
ink.line([0.0, 130.0], [w, 130.0], LINE);
if self.layout.selected_indices().len() > 1 {
self.alignment_inspector(ui, &ink, w);
return;
}
let Some(i) = self.layout.selected() else {
ink.text(0.0, 153.0, "Select a layer to edit or paste.", 17.0, TEXT);
ink.text(
0.0,
153.0,
"Select a layer, or drag a selection box.",
16.0,
TEXT,
);
ink.text(
0.0,
182.0,
"Shift-click to add or remove layers.",
13.0,
MUTED,
);
return;
};
let g = self.layout.layers()[i];
@ -426,7 +469,7 @@ impl Editor {
ink.text(
0.0,
579.0,
"Outside screen · use Fit layer to find it",
"Outside screen · use Fit selected to find it",
12.0,
AMBER,
);
@ -459,6 +502,88 @@ impl Editor {
MUTED,
);
}
fn alignment_inspector(&mut self, ui: &mut egui::Ui, ink: &Ink, w: f32) {
ink.text(0.0, 150.0, "2 layers selected", 25.0, TEXT);
ink.text(
0.0,
187.0,
"Drag or nudge to move the selection together.",
12.0,
MUTED,
);
ink.text(0.0, 225.0, "ALIGN TO", 11.0, MUTED);
let half = (w - 12.0) / 2.0;
for (index, title, target) in [
(0, "Selection bounds", AlignTarget::Selection),
(1, "Screen", AlignTarget::Screen),
(2, "Reference: Presenter", AlignTarget::Layer(0)),
(3, "Reference: Slides", AlignTarget::Layer(1)),
] {
let x = if index % 2 == 0 { 0.0 } else { half + 12.0 };
let y = 250.0 + (index / 2) as f32 * 42.0;
ink.button(x, y, half, title, self.align_target == target);
if click(ui, ink, [x, y, half, 34.0], title) {
self.align_target = target;
}
}
for (index, title, alignment) in [
(0, "Align left", Alignment::Left),
(1, "Align top", Alignment::Top),
(2, "Align right", Alignment::Right),
(3, "Align bottom", Alignment::Bottom),
(4, "Center X", Alignment::HorizontalCenter),
(5, "Center Y", Alignment::VerticalCenter),
] {
let x = if index % 2 == 0 { 0.0 } else { half + 12.0 };
let y = 350.0 + (index / 2) as f32 * 46.0;
ink.button(x, y, half, title, false);
if click(ui, ink, [x, y, half, 34.0], title) {
match self.layout.align(alignment, self.align_target) {
Ok(()) => self.sync(),
Err(e) => self.error = e,
}
}
}
ink.text(
0.0,
503.0,
"Alignment changes position, never size.",
12.0,
MUTED,
);
ink.text(0.0, 526.0, "A reference layer stays fixed.", 12.0, MUTED);
ink.line([0.0, 559.0], [w, 559.0], LINE);
ink.text(0.0, 581.0, "WEBRCS / CENTER POSITIONS", 11.0, CYAN);
for (row, i) in self.layout.selected_indices().into_iter().enumerate() {
let y = 615.0 + row as f32 * 80.0;
let [x, cy] = self.layout.layers()[i].center();
ink.text(0.0, y, label(i), 13.0, MUTED);
ink.text(
0.0,
y + 25.0,
&format!("H {} V {}", number(x), number(cy)),
19.0,
TEXT,
);
}
ink.button(0.0, 792.0, w, "Copy selected positions", true);
if click(ui, ink, [0.0, 792.0, w, 34.0], "copy-selected") {
self.copy(ui.ctx());
}
ink.text(
0.0,
849.0,
"Select one layer to edit its size or paste.",
12.0,
MUTED,
);
if !self.error.is_empty() {
ui.put(
Rect::from_min_size(ink.point(0.0, 880.0), Vec2::new(w, 60.0)),
egui::Label::new(egui::RichText::new(&self.error).color(AMBER)).wrap(),
);
}
}
fn workspace(&mut self, ui: &mut egui::Ui) {
let r = ui.max_rect();
let ink = Ink::new(ui, r);
@ -466,9 +591,9 @@ impl Editor {
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"),
(139.0, 103.0, "Fit selected"),
(254.0, 80.0, "Undo"),
(346.0, 80.0, "Redo"),
] {
ink.button(x, 67.0, w, text, false);
if click(ui, &ink, [x, 67.0, w, 34.0], text) {
@ -477,9 +602,8 @@ impl Editor {
self.zoom = 1.0;
self.pan = Vec2::ZERO;
}
"Fit layer" => {
if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
"Fit selected" => {
if let Some(g) = self.layout.selection_bounds() {
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();
@ -497,8 +621,8 @@ impl Editor {
}
}
}
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") {
ink.button(438.0, 67.0, 154.0, "Paste draw.io…", true);
if click(ui, &ink, [438.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);
@ -512,7 +636,8 @@ impl Editor {
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 {
if response.hovered() && !self.layout.dragging() && !self.panning && self.marquee.is_none()
{
let scroll = ui.input(|i| i.smooth_scroll_delta.y);
if scroll != 0.0
&& let Some(p) = pointer
@ -524,7 +649,9 @@ impl Editor {
origin = area.center() - Vec2::new(960.0, 540.0) * scale + self.pan * scale;
}
}
if response.drag_started() {
if response.drag_started_by(egui::PointerButton::Primary)
|| response.drag_started_by(egui::PointerButton::Middle)
{
ui.ctx().memory_mut(|m| {
if let Some(id) = m.focused() {
m.surrender_focus(id);
@ -537,7 +664,21 @@ impl Editor {
&& 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]);
let point = [p.x as f64, p.y as f64];
let shift = ui.input(|i| i.modifiers.shift);
if shift || self.layout.hit(point).is_none() {
let previous = self.layout.selection_mask();
let base = if shift { previous } else { [false; 2] };
self.marquee = Some(Marquee {
start: point,
end: point,
base,
previous,
});
self.layout.set_selection(base);
} else {
self.layout.start_drag(point);
}
self.sync();
}
}
@ -547,27 +688,46 @@ impl Editor {
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]);
let point = [p.x as f64, p.y as f64];
if let Some(m) = self.marquee.as_mut() {
m.end = point;
self.layout.select_region(m.start, point, m.base);
} else {
self.layout.drag_to(point);
}
self.sync();
}
}
if response.drag_stopped() {
if self.layout.dragging()
if (self.layout.dragging() || self.marquee.is_some())
&& let Some(p) = pointer
{
let p = (p - origin) / scale;
self.layout.drag_to([p.x as f64, p.y as f64]);
let point = [p.x as f64, p.y as f64];
if let Some(m) = self.marquee.as_mut() {
m.end = point;
self.layout.select_region(m.start, point, m.base);
} else {
self.layout.drag_to(point);
}
self.sync();
}
self.layout.finish_drag();
self.marquee = None;
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]));
let hit = self.layout.hit([p.x as f64, p.y as f64]);
if click_shift_modifier(ui) {
if let Some(i) = hit {
self.layout.toggle(i);
}
} else {
self.layout.select(hit);
}
self.sync();
ui.ctx().memory_mut(|m| {
if let Some(id) = m.focused() {
@ -614,7 +774,7 @@ impl Editor {
);
}
}
if self.layout.selected() == Some(i) {
if self.layout.selection_mask()[i] {
for corner in [
rect.left_top(),
rect.right_top(),
@ -645,6 +805,17 @@ impl Editor {
);
}
}
if let Some(m) = self.marquee {
let from = origin + Vec2::new(m.start[0] as f32, m.start[1] as f32) * scale;
let to = origin + Vec2::new(m.end[0] as f32, m.end[1] as f32) * scale;
screen.painter.rect(
Rect::from_two_pos(from, to),
0.0,
Color32::from_rgba_unmultiplied(102, 219, 239, 25),
Stroke::new(1.0_f32, CYAN),
StrokeKind::Inside,
);
}
if let Some(i) = self.layout.selected() {
let g = self.layout.layers()[i];
if !g.outside() {
@ -692,7 +863,7 @@ impl Editor {
ink.text(
24.0,
r.height() - 57.0,
"Drag layer · Arrows 1 px · Shift 10 px · Ctrl/Cmd-V paste",
"Drag to move or box-select · Shift-click toggles selection",
12.0,
MUTED,
);
@ -705,6 +876,26 @@ impl Editor {
);
}
}
// Use the modifiers attached to the click, even if Shift was released later
// in the same input frame.
fn click_shift_modifier(ui: &egui::Ui) -> bool {
ui.input(|input| {
input
.events
.iter()
.rev()
.find_map(|event| match event {
egui::Event::PointerButton {
button: egui::PointerButton::Primary,
pressed: false,
modifiers,
..
} => Some(modifiers.shift),
_ => None,
})
.unwrap_or(input.modifiers.shift)
})
}
fn click(ui: &egui::Ui, ink: &Ink, b: [f32; 4], id: impl std::hash::Hash) -> bool {
let clicked = ui
.interact(
@ -757,8 +948,8 @@ impl Editor {
ink.text(
116.0,
10.0,
if self.layout.selected().is_some() {
"draw.io geometry · 1 unit = 1 px"
if !self.layout.selected_indices().is_empty() {
"Shift-click or drag a box to select layers"
} else {
"Select a layer to move or paste"
},
@ -778,7 +969,9 @@ impl Editor {
.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::ScrollArea::vertical()
.drag_to_scroll(false)
.show(ui, |ui| self.inspector(ui));
});
egui::CentralPanel::default()
.frame(egui::Frame::NONE.fill(BG))
@ -1041,4 +1234,153 @@ mod tests {
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
fn frame_shift(
app: &mut Editor,
ctx: &egui::Context,
events: Vec<egui::Event>,
) -> egui::FullOutput {
ctx.run(
egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(1440.0, 940.0))),
events,
modifiers: egui::Modifiers::SHIFT,
..Default::default()
},
|ctx| app.ui(ctx),
)
}
fn click_shift(app: &mut Editor, ctx: &egui::Context, p: Pos2) {
let event = |pressed| egui::Event::PointerButton {
pos: p,
button: egui::PointerButton::Primary,
pressed,
modifiers: egui::Modifiers::SHIFT,
};
frame_shift(app, ctx, vec![egui::Event::PointerMoved(p), event(true)]);
frame(app, ctx, vec![event(false)]); // Shift released by the end of this frame.
}
fn layer_rects(output: &egui::FullOutput) -> Vec<Rect> {
output
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::epaint::Shape::Rect(r) if r.fill == Color32::from_rgb(23, 59, 80) => {
Some(r.rect)
}
_ => None,
})
.collect()
}
#[test]
fn shift_click_toggles_canvas_and_list_selection() {
let mut app = Editor::default();
let ctx = egui::Context::default();
let output = frame(&mut app, &ctx, vec![]);
let rects = layer_rects(&output);
assert_eq!(rects.len(), 2);
click_shift(&mut app, &ctx, rects[0].center());
assert_eq!(app.layout.selected_indices(), vec![0, 1]);
click_shift(&mut app, &ctx, rects[1].center());
assert_eq!(app.layout.selected(), Some(0));
click_shift(&mut app, &ctx, Pos2::new(1180.0, 180.0));
assert_eq!(app.layout.selected_indices(), vec![0, 1]);
let row = ctx
.read_response(egui::Id::new(("layer", 0_usize)))
.unwrap()
.rect;
click_shift(&mut app, &ctx, row.center());
assert_eq!(app.layout.selection_mask(), [false, true]);
}
#[test]
fn marquee_selects_both_at_different_camera_transforms_without_moving_them() {
for zoom in [0.6, 1.0] {
let mut app = Editor {
zoom,
pan: Vec2::new(10.0, -8.0),
..Default::default()
};
let ctx = egui::Context::default();
let output = frame(&mut app, &ctx, vec![]);
let before = *app.layout.layers();
let rects = layer_rects(&output);
let area = rects[0].union(rects[1]).expand(10.0);
let start = area.left_top();
let end = area.right_bottom();
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start), mouse(start, true)],
);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
assert!(app.marquee.is_some());
frame(&mut app, &ctx, vec![mouse(end, false)]);
assert_eq!(app.layout.selected_indices(), vec![0, 1]);
assert!(app.marquee.is_none());
assert_eq!(*app.layout.layers(), before);
}
}
#[test]
fn escape_cancels_selection_box_and_restores_previous_selection() {
let mut app = Editor::default();
let ctx = egui::Context::default();
let output = frame(&mut app, &ctx, vec![]);
let rects = layer_rects(&output);
let area = rects[0].union(rects[1]).expand(10.0);
let start = area.left_top();
let end = area.right_bottom();
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start), mouse(start, true)],
);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
assert_eq!(app.layout.selected_indices(), vec![0, 1]);
frame(&mut app, &ctx, vec![key(egui::Key::Escape)]);
frame(&mut app, &ctx, vec![mouse(end, false)]);
assert_eq!(app.layout.selected(), Some(1));
assert!(app.marquee.is_none());
}
#[test]
fn alignment_button_updates_selected_layers_and_undo_restores() {
let mut app = Editor::default();
let ctx = egui::Context::default();
app.layout
.apply(
0,
Geometry {
x: 90.0,
y: 60.0,
width: 300.0,
height: 200.0,
},
)
.unwrap();
app.layout.set_selection([true; 2]);
let before = *app.layout.layers();
let output = frame(&mut app, &ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::epaint::Shape::Text(t) if t.galley.job.text == "Align top" => {
Some(t.pos + Vec2::new(20.0, 6.0))
}
_ => None,
})
.unwrap();
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
assert_eq!(app.layout.layers()[1].y, 60.0);
assert_eq!(app.layout.layers()[1].x, before[1].x);
assert_eq!(app.layout.layers()[0], before[0]);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
app.open_paste(include_str!("../tests/fixtures/drawio-rectangle.txt").into());
assert!(app.paste.is_none());
assert!(app.error.contains("exactly one"));
}
}

View File

@ -80,13 +80,32 @@ impl Corner {
}
}
/// Edge or center line to align, without resizing layers.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Alignment {
Left,
Right,
Top,
Bottom,
HorizontalCenter,
VerticalCenter,
}
/// Explicit alignment reference, independent of selection order.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum AlignTarget {
#[default]
Selection,
Screen,
Layer(usize),
}
/// Two-layer document with one undo record per complete gesture/edit.
pub struct Layout {
layers: [Geometry; 2],
selected: Option<usize>,
selected: [bool; 2],
undo: Vec<[Geometry; 2]>,
redo: Vec<[Geometry; 2]>,
drag: Option<(usize, [Geometry; 2], [f64; 2])>,
drag: Option<([bool; 2], [Geometry; 2], [f64; 2])>,
}
impl Default for Layout {
fn default() -> Self {
@ -105,7 +124,7 @@ impl Default for Layout {
height: 360.0,
},
],
selected: Some(1),
selected: [false, true],
undo: Vec::new(),
redo: Vec::new(),
drag: None,
@ -116,12 +135,114 @@ impl Layout {
pub fn layers(&self) -> &[Geometry; 2] {
&self.layers
}
/// A single selected layer, or None for zero/multiple selections.
pub fn selected(&self) -> Option<usize> {
let indices = self.selected_indices();
if indices.len() == 1 {
Some(indices[0])
} else {
None
}
}
pub fn selected_indices(&self) -> Vec<usize> {
(0..2).filter(|i| self.selected[*i]).collect()
}
pub fn selection_mask(&self) -> [bool; 2] {
self.selected
}
pub fn select(&mut self, index: Option<usize>) {
pub fn set_selection(&mut self, selected: [bool; 2]) {
self.finish_drag();
self.selected = index.filter(|i| *i < 2);
self.selected = selected;
}
pub fn select(&mut self, index: Option<usize>) {
self.set_selection(std::array::from_fn(|i| index == Some(i)));
}
pub fn toggle(&mut self, index: usize) {
self.finish_drag();
if let Some(selected) = self.selected.get_mut(index) {
*selected = !*selected;
}
}
/// Select rectangles intersecting the marquee; base supplies Shift-additive selection.
pub fn select_region(&mut self, start: [f64; 2], end: [f64; 2], base: [bool; 2]) {
let left = start[0].min(end[0]);
let right = start[0].max(end[0]);
let top = start[1].min(end[1]);
let bottom = start[1].max(end[1]);
self.set_selection(std::array::from_fn(|i| {
let g = self.layers[i];
base[i]
|| (g.x <= right && g.x + g.width >= left && g.y <= bottom && g.y + g.height >= top)
}));
}
pub fn selection_bounds(&self) -> Option<Geometry> {
let mut bounds = None::<Geometry>;
for i in self.selected_indices() {
let g = self.layers[i];
bounds = Some(match bounds {
None => g,
Some(b) => {
let x = b.x.min(g.x);
let y = b.y.min(g.y);
Geometry {
x,
y,
width: (b.x + b.width).max(g.x + g.width) - x,
height: (b.y + b.height).max(g.y + g.height) - y,
}
}
});
}
bounds
}
/// Align only selected rectangles; preserve size and the unrelated axis.
pub fn align(&mut self, alignment: Alignment, target: AlignTarget) -> Result<(), String> {
self.finish_drag();
let bounds = self.selection_bounds().ok_or("Select layers to align.")?;
let reference = match target {
AlignTarget::Selection => bounds,
AlignTarget::Screen => Geometry {
x: 0.0,
y: 0.0,
width: 1920.0,
height: 1080.0,
},
AlignTarget::Layer(i) => {
if !self.selected.get(i).copied().unwrap_or(false) {
return Err("Select the reference layer too.".into());
}
self.layers[i]
}
};
let mut next = self.layers;
for i in self.selected_indices() {
if target == AlignTarget::Layer(i) {
continue;
}
let g = &mut next[i];
match alignment {
Alignment::Left => g.x = reference.x,
Alignment::Right => g.x = reference.x + reference.width - g.width,
Alignment::Top => g.y = reference.y,
Alignment::Bottom => g.y = reference.y + reference.height - g.height,
Alignment::HorizontalCenter => {
g.x = reference.x + (reference.width - g.width) / 2.0
}
Alignment::VerticalCenter => {
g.y = reference.y + (reference.height - g.height) / 2.0
}
}
}
self.commit(next)
}
fn commit(&mut self, next: [Geometry; 2]) -> Result<(), String> {
for g in next {
g.validate()?;
}
let before = self.layers;
self.layers = next;
self.remember(before);
Ok(())
}
pub fn hit(&self, point: [f64; 2]) -> Option<usize> {
(0..2).rev().find(|i| self.layers[*i].contains(point))
@ -147,36 +268,36 @@ impl Layout {
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
},
)?;
self.finish_drag();
let mut next = self.layers;
for i in self.selected_indices() {
next[i].x += dx;
next[i].y += dy;
}
Ok(())
self.commit(next)
}
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));
if let Some(i) = self.hit(point) {
if !self.selected[i] {
self.select(Some(i));
}
self.drag = Some((self.selected, self.layers, point));
} else {
self.select(None);
}
}
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;
if let Some((selected, before, start)) = self.drag {
let mut next = before;
for i in 0..2 {
if selected[i] {
next[i].x += (point[0] - start[0]).round();
next[i].y += (point[1] - start[1]).round();
}
}
if next.iter().all(|g| g.validate().is_ok()) {
self.layers = next;
}
}
}

View File

@ -332,3 +332,178 @@ fn each_pasted_rectangle_keeps_its_own_outline_width() {
38.0
);
}
#[test]
fn selection_toggle_and_marquee_are_independent_of_geometry_history() {
let mut l = Layout::default();
let original = *l.layers();
l.toggle(0);
assert_eq!(l.selected_indices(), vec![0, 1]);
assert_eq!(l.selected(), None);
l.toggle(1);
assert_eq!(l.selected(), Some(0));
l.toggle(0);
assert!(l.selected_indices().is_empty());
l.select_region([1800.0, 600.0], [100.0, 100.0], [false; 2]);
assert_eq!(l.selected_indices(), vec![0, 1]);
l.select_region([100.0, 100.0], [125.0, 185.0], [false, true]);
assert_eq!(l.selected_indices(), vec![0, 1]);
assert_eq!(*l.layers(), original);
l.undo();
assert_eq!(*l.layers(), original);
}
#[test]
fn selected_layers_drag_and_nudge_together_with_atomic_undo() {
let mut l = Layout::default();
l.set_selection([true; 2]);
let before = *l.layers();
l.start_drag([130.0, 190.0]);
l.drag_to([155.0, 200.0]);
l.finish_drag();
for (i, g) in before.iter().enumerate() {
assert_eq!(
l.layers()[i],
Geometry {
x: g.x + 25.0,
y: g.y + 10.0,
..*g
}
);
}
l.undo();
assert_eq!(*l.layers(), before);
l.redo();
l.nudge(1.0, -10.0).unwrap();
for (i, g) in before.iter().enumerate() {
assert_eq!(
l.layers()[i],
Geometry {
x: g.x + 26.0,
y: g.y,
..*g
}
);
}
l.undo();
l.undo();
assert_eq!(*l.layers(), before);
l.start_drag([130.0, 190.0]);
l.drag_to([150.0, 220.0]);
l.cancel_drag();
assert_eq!(*l.layers(), before);
}
#[test]
fn align_edges_and_centers_to_explicit_targets_without_resizing() {
use midra_layout::{AlignTarget as T, Alignment as A};
let initial = [
Geometry {
x: 100.5,
y: 70.25,
width: 300.0,
height: 210.0,
},
Geometry {
x: 700.25,
y: 350.5,
width: 100.0,
height: 80.0,
},
];
for target in [T::Selection, T::Screen, T::Layer(0), T::Layer(1)] {
for alignment in [
A::Left,
A::Right,
A::Top,
A::Bottom,
A::HorizontalCenter,
A::VerticalCenter,
] {
let mut l = Layout::default();
for (i, g) in initial.iter().enumerate() {
l.apply(i, *g).unwrap();
}
l.set_selection([true; 2]);
let reference = match target {
T::Screen => Geometry {
x: 0.0,
y: 0.0,
width: 1920.0,
height: 1080.0,
},
T::Selection => l.selection_bounds().unwrap(),
T::Layer(i) => initial[i],
};
l.align(alignment, target).unwrap();
for (i, g) in l.layers().iter().enumerate() {
assert_eq!([g.width, g.height], [initial[i].width, initial[i].height]);
let (actual, wanted) = match alignment {
A::Left => (g.x, reference.x),
A::Right => (g.x + g.width, reference.x + reference.width),
A::Top => (g.y, reference.y),
A::Bottom => (g.y + g.height, reference.y + reference.height),
A::HorizontalCenter => (g.center()[0], reference.center()[0]),
A::VerticalCenter => (g.center()[1], reference.center()[1]),
};
assert!((actual - wanted).abs() < 1e-9);
if matches!(alignment, A::Left | A::Right | A::HorizontalCenter) {
assert_eq!(g.y, initial[i].y);
} else {
assert_eq!(g.x, initial[i].x);
}
}
if let T::Layer(i) = target {
assert_eq!(l.layers()[i], initial[i]);
}
let aligned = *l.layers();
l.undo();
assert_eq!(*l.layers(), initial);
l.redo();
assert_eq!(*l.layers(), aligned);
}
}
}
#[test]
fn alignment_refuses_invalid_reference_and_failed_group_moves_are_atomic() {
use midra_layout::{AlignTarget as T, Alignment as A};
let mut l = Layout::default();
let before = *l.layers();
assert!(l.align(A::Top, T::Layer(0)).is_err());
assert_eq!(*l.layers(), before);
l.select(None);
assert!(l.align(A::Left, T::Screen).is_err());
l.apply(
1,
Geometry {
x: 1_000_000.0,
..before[1]
},
)
.unwrap();
l.set_selection([true; 2]);
let before = *l.layers();
assert!(l.nudge(1.0, 0.0).is_err());
assert_eq!(*l.layers(), before);
l.start_drag([130.0, 190.0]);
l.drag_to([140.0, 190.0]);
l.finish_drag();
assert_eq!(*l.layers(), before);
}
#[test]
fn alignment_moves_only_selected_layers_and_is_order_independent() {
use midra_layout::{AlignTarget as T, Alignment as A};
let mut l = Layout::default();
let before = *l.layers();
l.align(A::Left, T::Screen).unwrap();
assert_eq!(l.layers()[0], before[0]);
assert_eq!(l.layers()[1].x, 0.0);
l.undo();
l.select(Some(0));
l.toggle(1);
l.align(A::Left, T::Selection).unwrap();
let first = *l.layers();
l.undo();
l.select(Some(1));
l.toggle(0);
l.align(A::Left, T::Selection).unwrap();
assert_eq!(*l.layers(), first);
}

View File

@ -1,10 +1,11 @@
# Midra layout helper: plan and visual proposals
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.
geometry paste with review, two-layer multi-selection and group movement, box
selection, explicit-target alignment, 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,
Custom resolution, source/input formats, image import,
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.
@ -179,17 +180,20 @@ Gate: supported data places the selected rectangle correctly; malformed or
ambiguous data makes no changes. Ship the basic format first if no external
software format has yet been selected; do not claim that completes an adapter.
### 7. Later: explicit multi-layer alignment
### 7. Explicit multi-layer alignment
- [ ] Add Align top and Align left first; show the alignment target explicitly:
- [x] Add Align top and Align left; show the alignment target explicitly:
screen, selection bounds or a named reference layer.
- [ ] For a reference layer, keep that layer fixed and move only the others.
- [x] For a reference layer, keep that layer fixed and move only the others.
For selection bounds, align to the minimum top/left edge. For the screen,
align to coordinate zero on the selected axis.
- [ ] Preserve sizes and the other axis, preview the affected selection, and
- [x] Preserve sizes and the other axis, preview the affected selection, and
make each alignment a single undoable operation.
- [ ] Extend to right/bottom/center alignment and more layers only when needed,
within verified device capabilities. No distribution or constraint system yet.
- [x] Add right/bottom/center alignment using the same explicit targets.
- [x] Add Shift-click toggling in the viewport/list, left-drag box selection,
Shift-drag additive selection and Escape cancellation. Group movement/nudging
preserves spacing and uses one undo step per action.
- [ ] Extend beyond two layers under step 11. No distribution or constraint system yet.
Gate: two differently sized layers align exactly against the chosen target,
regardless of selection order except when explicitly choosing a reference layer.
@ -387,15 +391,15 @@ useful features can be incorporated into A without maintaining two different app
### C. Focus desk
A wider viewport and narrower contextual inspector. This proposal shows the
future multi-selection state: a named reference layer, explicit alignment actions
A wider viewport and narrower contextual inspector. This proposal illustrates the
multi-selection state: a named reference layer, explicit alignment actions
and a compact per-layer coordinate table. The layer list remains on the right.
![Concept C: compact workspace with two selected layers](design/midra-layout/c-concept.svg)
Best for repeated placement and comparison once the basic workflow is familiar.
Less space for numeric explanations makes it weaker as the initial default.
The alignment state belongs to step 7; it does not imply a larger first release.
The alignment state is now available under step 7; the SVG remains a design concept.
### Shared interaction and responsive behavior

View File

@ -66,28 +66,54 @@ 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**.
- Click a layer or its list entry to select it alone. **Shift-click** toggles that
layer in the selection. In overlaps, the upper layer wins; the list lets you
reach the lower layer. Clicking empty canvas clears selection; Shift-clicking
empty canvas preserves it.
- **Left-drag on empty canvas** draws a selection box, selecting every rectangle
it intersects, in either drag direction. **Shift-drag** draws an additive box,
including when starting over a layer. Escape cancels the box and restores the
previous selection.
- Drag a selected layer to move the whole selection together; dragging an
unselected layer selects and moves it alone. Movement uses whole-screen-pixel
deltas and preserves fractional starting positions, sizes and relative spacing.
Selection handles indicate bounds; resizing uses the single-layer numeric fields.
- Arrow keys move the selection by **1 px**; Shift-arrow moves it 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.
dialog it closes the preview without applying it. Group drags cancel atomically.
- **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
edits. Each drag, alignment, 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.
pans. **Fit screen** resets the view; **Fit selected** frames the entire selection.
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
- **Copy position values** (or **Copy selected positions** for multiple layers)
copies labeled plain text with each selected layer's center position and
dimensions. This is not a native WebRCS clipboard payload.
## Align selected layers
Select both layers to reveal the alignment inspector. Choose an explicit target:
- **Selection bounds** uses the selected rectangles' combined bounds at the time
of the action. Align left/top uses the minimum left/top; right/bottom uses the
maximum right/bottom. Selection order has no effect.
- **Screen** aligns to the screen edges or center lines.
- **Reference: Presenter / Slides** aligns to that selected layer's edges or
center lines. The named reference remains fixed.
Use **Align left**, **Align right**, **Align top**, **Align bottom**, **Center X**
(horizontal centers) or **Center Y** (vertical centers). Each action changes only
the relevant position axis, never size, and is one undo step. The inspector lists
each layer's resulting center coordinates. Single-layer numeric fields are
replaced by alignment controls during multi-selection; no mixed values are shown
as if they belonged to one layer. Select exactly one layer to paste or resize.
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.
@ -96,7 +122,7 @@ identifies its target explicitly and changes only that layer.
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
formats, custom output resolution, image import, cropping and persistent
session files are future work. Sessions currently live only in memory.
[Layer management and export scope](midra-layout-plan.md#11-later-stretch-goal-layer-management-and-export-scope)
@ -121,7 +147,9 @@ 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.
corner conversion, group drag/undo, selection boxes, alignment targets, and GUI
paste/focus behavior. Layer-list scrolling uses the wheel or scrollbar so dragging
across list entries cannot accidentally scroll while selecting.
See the [project plan](midra-layout-plan.md) and
[resolution/cropping specification](midra-layout-resolutions.md) for future work.