Allow direct per-rectangle paste mapping without a selection
Beffroi/beffroi-tools/pipeline/head This commit looks good Details

This commit is contained in:
Dandaedre 2026-11-13 18:00:52 +01:00
parent c4b269319c
commit b13f9f73e8
4 changed files with 163 additions and 10 deletions

View File

@ -63,6 +63,7 @@ struct Marquee {
struct Paste {
targets: Vec<usize>,
target_ids: Vec<usize>,
available_ids: Vec<usize>,
text: String,
shapes: Vec<DetectedShape>,
mapping: Vec<Option<usize>>,
@ -140,7 +141,11 @@ impl Paste {
} else {
Vec::new()
};
layout.apply_import_with_zoom(&values, &zooms)
if self.targets.is_empty() {
layout.apply_mapped_import_with_zoom(&values, &zooms)
} else {
layout.apply_import_with_zoom(&values, &zooms)
}
}
fn values(&self, layout: &Layout) -> Result<Vec<(usize, Geometry)>, String> {
if !self.include_size
@ -155,7 +160,7 @@ impl Paste {
if count == 0 {
return Err("No rectangles to import. Include at least one rectangle.".into());
}
if count > self.targets.len() {
if !self.targets.is_empty() && count > self.targets.len() {
return Err(format!(
"Layer count mismatch: {} selected, {} detected ({} excluded). Choose at least {} destination layer(s), or supply at most {} rectangle(s).",
self.targets.len(),
@ -185,7 +190,19 @@ impl Paste {
}
let target =
self.mapping[row].ok_or("Choose a destination for each detected rectangle.")?;
if !self.targets.contains(&target) || values.iter().any(|(i, _)| *i == target) {
if target >= layout.layers().len()
|| self.available_ids.get(target).copied() != Some(layout.layer_info(target).id)
|| !layout.visible(target)
|| layout.locked(target)
{
return Err(
"Destination unavailable. Choose a visible, unlocked layer from this review."
.into(),
);
}
if (!self.targets.is_empty() && !self.targets.contains(&target))
|| values.iter().any(|(i, _)| *i == target)
{
return Err("Each imported rectangle needs a different selected destination; choose a different destination for duplicate mappings.".into());
}
values.push((target, self.geometry(shape, layout.layers()[target])?));
@ -441,6 +458,9 @@ impl Editor {
fn open_paste(&mut self, text: String) {
let targets = self.layout.selected_indices();
let mut p = Paste {
available_ids: (0..self.layout.layers().len())
.map(|i| self.layout.layer_info(i).id)
.collect(),
target_ids: targets
.iter()
.map(|i| self.layout.layer_info(*i).id)
@ -712,7 +732,11 @@ impl Editor {
p.target_ids = p.targets.iter().map(|&i| self.layout.layer_info(i).id).collect();
p.reset_mapping();
}
ui.label(format!("Selected destinations: {}",p.targets.iter().map(|i|self.layout.layer_label(*i)).collect::<Vec<_>>().join(", ")));
if p.targets.is_empty() {
ui.label("Choose a destination beside each rectangle below; no viewport selection is needed.");
} else {
ui.label(format!("Selected destinations: {}",p.targets.iter().map(|i|self.layout.layer_label(*i)).collect::<Vec<_>>().join(", ")));
}
ui.label("Paste Midra Layout values, draw.io clipboard data or SVG XML, or import SVG.");
egui::ScrollArea::vertical().max_height((ctx.screen_rect().height()-360.0).max(150.0)).show(ui,|ui| {
if ui.add(egui::TextEdit::multiline(&mut p.text).desired_rows(3).desired_width(f32::INFINITY)).changed() {p.shapes.clear();p.error.clear();}
@ -737,7 +761,7 @@ impl Editor {
if !p.include_size {ui.small("Outline adjustment requires Format. Position uses the source top-left when enabled.");}
ui.separator();
ui.strong("Detected rectangles / destination layers");
ui.small("Map each rectangle to one selected layer. Unmapped selected layers stay unchanged.");
ui.small("Map each rectangle to one destination. Unmapped layers stay unchanged.");
let mut reset_mapping=false;
for row in 0..p.shapes.len() {
let shape=p.shapes[row].clone();
@ -751,7 +775,13 @@ impl Editor {
}
if !p.ignored[row] {
egui::ComboBox::from_id_salt("destination").selected_text(p.mapping[row].map(|i| self.layout.layer_label(i)).unwrap_or_else(|| "Choose destination…".into())).show_ui(ui,|ui| {
for target in &p.targets {ui.selectable_value(&mut p.mapping[row],Some(*target),self.layout.layer_label(*target));}
ui.selectable_value(&mut p.mapping[row], None, "Choose destination…");
let candidates: Vec<_> = if p.targets.is_empty() { (0..self.layout.layers().len()).collect() } else { p.targets.clone() };
for target in candidates {
ui.add_enabled_ui(self.layout.visible(target) && !self.layout.locked(target), |ui| {
ui.selectable_value(&mut p.mapping[row],Some(target),self.layout.layer_label(target));
});
}
});
if let Some(target)=p.mapping[row] {
let before=self.layout.layers()[target];
@ -3468,6 +3498,55 @@ mod tests {
assert_eq!(app.reference.as_ref().unwrap().texture.id(), texture);
}
#[test]
fn paste_without_selection_maps_directly_from_rectangle_dropdown() {
let mut app = Editor::default();
let ctx = egui::Context::default();
app.layout.select(None);
let before = app.layout.layers().clone();
app.open_paste(include_str!("../tests/fixtures/drawio-rectangle.txt").into());
assert!(app.paste.as_ref().unwrap().targets.is_empty());
fn text_position(output: &egui::FullOutput, label: &str) -> Pos2 {
output
.shapes
.iter()
.rev()
.find_map(|s| match &s.shape {
egui::epaint::Shape::Text(t) if t.galley.job.text == label => {
Some(t.pos + Vec2::new(12.0, 6.0))
}
_ => None,
})
.unwrap_or_else(|| panic!("Missing label {label}"))
}
frame(&mut app, &ctx, vec![]);
let output = frame(&mut app, &ctx, vec![]);
let pos = text_position(&output, "Choose destination…");
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
let output = frame(&mut app, &ctx, vec![]);
let pos = text_position(&output, &app.layout.layer_label(0));
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
let paste = app.paste.as_ref().unwrap();
assert!(paste.targets.is_empty());
assert_eq!(paste.mapping, vec![Some(0)]);
assert_eq!(*app.layout.layers(), before);
paste.apply(&mut app.layout).unwrap();
assert_eq!(app.layout.layers()[0].width, 945.0);
assert_eq!(app.layout.layers()[1], before[1]);
assert!(app.layout.selected_indices().is_empty());
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
}
#[test]
fn import_can_choose_destination_inside_review_without_initial_selection() {
let mut app = Editor::default();
let ctx = egui::Context::default();

View File

@ -940,6 +940,28 @@ impl Layout {
self.remember(before);
Ok(())
}
/// Apply explicit destination indices without changing the viewport selection.
/// Mappings must be unique, visible and unlocked; failures are atomic.
pub fn apply_mapped_import_with_zoom(
&mut self,
values: &[(usize, Geometry)],
zooms: &[(usize, f64)],
) -> Result<(), String> {
if values.iter().any(|(i, _)| !self.selectable(*i)) {
return Err("Choose visible, unlocked destination layers.".into());
}
let mut draft = self.clone();
let selection: Vec<_> = (0..self.layers.len())
.map(|i| values.iter().any(|(target, _)| *target == i))
.collect();
draft.set_selection(selection);
draft.apply_import_with_zoom(values, zooms)?;
self.finish_drag();
let before = self.snapshot();
self.restore(draft.snapshot());
self.remember(before);
Ok(())
}
/// Import geometry and optional crop zoom together as one atomic edit.
pub fn apply_import_with_zoom(
&mut self,

View File

@ -263,3 +263,52 @@ fn geometry_and_zoom_import_is_atomic_and_clamps_offsets_on_zoom_out() {
assert_eq!(*l.layers(), before);
assert_eq!(*l.formats(), formats);
}
#[test]
fn explicit_mapping_without_selection_is_atomic_and_preserves_selection() {
let mut layout = Layout::default();
layout.select(None);
let before = layout.layers().clone();
let formats = layout.formats().clone();
let a = Geometry {
x: 12.0,
y: 34.0,
width: 400.0,
height: 300.0,
};
let b = Geometry { x: 600.0, ..a };
assert!(
layout
.apply_mapped_import_with_zoom(&[(0, a), (0, b)], &[])
.is_err()
);
assert!(
layout
.apply_mapped_import_with_zoom(&[(9, a)], &[])
.is_err()
);
assert!(
layout
.apply_mapped_import_with_zoom(&[(1, a), (0, b)], &[(0, f64::NAN)])
.is_err()
);
assert_eq!(*layout.layers(), before);
assert_eq!(*layout.formats(), formats);
layout
.apply_mapped_import_with_zoom(&[(1, a), (0, b)], &[(1, 2.0)])
.unwrap();
assert_eq!(*layout.layers(), [b, a]);
assert!(layout.selected_indices().is_empty());
layout.undo();
assert_eq!(*layout.layers(), before);
assert_eq!(*layout.formats(), formats);
layout.redo();
assert_eq!(*layout.layers(), [b, a]);
assert!(layout.selected_indices().is_empty());
layout.set_locked(1, true);
assert!(
layout
.apply_mapped_import_with_zoom(&[(1, b)], &[])
.is_err()
);
}

View File

@ -20,9 +20,12 @@ cargo run --locked -p midra-layout
area and click **Read geometry**. **Import → SVG file…** opens an SVG file in the
same review window; raw SVG XML can also be pasted. **Import → Clipboard values**
reads the clipboard directly and opens the mapping review.
3. Review each detected rectangle and choose its destination layer. Initial
3. Review each detected rectangle and choose its destination layer. With nothing
selected, each rectangle's dropdown lists all editor layers (hidden/locked
destinations are disabled). Map the rectangles individually; no selection
step is required, and applying leaves the viewport selection unchanged. Initial
mapping follows document order and the selected layer list. Each rectangle must map to a different
selected destination. Fewer rectangles than selected layers are allowed;
destination (restricted to the selection when one exists). Fewer rectangles than selected layers are allowed;
unmapped layers stay unchanged. Too many rectangles or duplicate mappings
block Apply and explain what needs changing. Nothing changes yet.
4. Choose independently what to paste: **Format (width / height)**, **Position**,
@ -585,8 +588,8 @@ You can choose layers without returning to the viewport:
- **Import → Choose destination layers…**, and the same picker inside the
clipboard/SVG review, select the destinations. Paste and SVG import can open
with nothing selected. Then map each detected rectangle using its destination
dropdown. There must be at least as many chosen destinations as imported rectangles
with nothing selected: map each detected rectangle directly to an available
layer using its destination dropdown. When using a selection, there must be at least as many chosen destinations as imported rectangles
after ignoring an SVG background. Map to any subset of them; other layers stay
unchanged. Duplicate mappings and empty imports remain invalid.
- **Project → Export SVG → Choose layers to export…** selects the group for