diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index e94f2a5..138dc40 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -42,6 +42,8 @@ struct Paste { svg: bool, note: String, include_size: bool, + include_position: bool, + include_zoom: bool, include_outline: bool, error: String, } @@ -79,7 +81,48 @@ impl Paste { } } } + fn zoom_available(&self) -> bool { + self.shapes + .iter() + .zip(&self.ignored) + .any(|(s, ignored)| !ignored && s.zoom.is_some()) + } + fn geometry(&self, shape: &DetectedShape, before: Geometry) -> Result { + let mut g = shape.paste_geometry(before, self.include_size, self.include_outline)?; + if !self.include_position { + g.x = before.x; + g.y = before.y; + } + Ok(g) + } + fn apply(&self, layout: &mut Layout) -> Result<(), String> { + let values = self.values(layout)?; + let zooms: Vec<_> = if self.include_zoom { + self.shapes + .iter() + .enumerate() + .filter_map(|(row, s)| { + if self.ignored[row] { + None + } else { + s.zoom.map(|zoom| (self.mapping[row].unwrap(), zoom)) + } + }) + .collect() + } else { + Vec::new() + }; + layout.apply_import_with_zoom(&values, &zooms) + } fn values(&self, layout: &Layout) -> Result, String> { + if !self.include_size + && !self.include_position + && !(self.include_zoom && self.zoom_available()) + { + return Err( + "Choose at least one available value to paste: format, position or zoom.".into(), + ); + } let count = self.ignored.iter().filter(|v| !**v).count(); if count != self.targets.len() { return Err(format!( @@ -107,14 +150,7 @@ impl Paste { if !self.targets.contains(&target) || values.iter().any(|(i, _)| *i == target) { return Err("Each selected layer must be mapped exactly once; choose a different destination for duplicate mappings.".into()); } - values.push(( - target, - shape.paste_geometry( - layout.layers()[target], - self.include_size, - self.include_outline, - )?, - )); + values.push((target, self.geometry(shape, layout.layers()[target])?)); } Ok(values) } @@ -263,6 +299,8 @@ impl Editor { svg: false, note: String::new(), include_size: true, + include_position: true, + include_zoom: true, include_outline: false, error: String::new(), }; @@ -374,12 +412,13 @@ impl Editor { let g = self.layout.layers()[i]; let [h, v] = g.center(); format!( - "{} — visible box (device container unverified)\nHorizontal: {} px\nVertical: {} px\nWidth: {} px\nHeight: {} px", + "{} — visible box (device container unverified)\nHorizontal: {} px\nVertical: {} px\nWidth: {} px\nHeight: {} px\nCrop zoom: {} %", label(i), midra_layout::export_pixels(h), midra_layout::export_pixels(v), midra_layout::export_pixels(g.width), - midra_layout::export_pixels(g.height) + midra_layout::export_pixels(g.height), + number(self.layout.formats().mapping(i, g).unwrap().framing.zoom * 100.0) ) }) .collect(); @@ -508,17 +547,28 @@ impl Editor { if !p.error.is_empty() {ui.colored_label(AMBER,&p.error);} if p.shapes.is_empty() {return;} ui.label(&p.note); - ui.checkbox(&mut p.include_size,"Include size / format (otherwise position only)"); + ui.horizontal(|ui| { + ui.checkbox(&mut p.include_size,"Format (width / height)"); + ui.checkbox(&mut p.include_position,"Position"); + let available=p.zoom_available(); + let mut zoom=p.include_zoom && available; + if ui.add_enabled(available,egui::Checkbox::new(&mut zoom,"Crop zoom")).changed() {p.include_zoom=zoom;} + }); + if !p.zoom_available() {ui.small("Crop zoom is not included in this data.");} + ui.small("Unchecked values keep the destination settings. Format changes may adjust existing crops to fit."); ui.add_enabled(p.include_size && p.shapes.iter().any(|s|s.outline.iter().any(|v|*v>0.0)),egui::Checkbox::new(&mut p.include_outline,"Include outline in bounds")); - ui.small("Bounds only; source format, colors and outline appearance are not imported."); - if !p.include_size {ui.small("Position-only uses the original top-left; outline adjustment requires size import.");} + ui.small("Source format, crop offsets, colors and outline appearance are not imported."); + 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"); let mut reset_mapping=false; - for (row,shape) in p.shapes.iter().enumerate() { + for row in 0..p.shapes.len() { + let shape=p.shapes[row].clone(); ui.push_id(row,|ui| { ui.label(format!("{} · {}",row+1,shape.id)); ui.small(bounds(shape.geometry)); + if let Some(zoom)=shape.zoom {ui.small(format!("Crop zoom: {:.1}%{}",zoom*100.0,if p.include_zoom { " (will apply)" } else { " (not applied)" }));} + else if p.include_zoom && p.zoom_available() {ui.small("No crop zoom in this rectangle; destination zoom is retained.");} if p.svg && shape.background { reset_mapping|=ui.checkbox(&mut p.ignored[row],"Ignore full-page background").changed(); } @@ -528,7 +578,7 @@ impl Editor { }); if let Some(target)=p.mapping[row] { let before=self.layout.layers()[target]; - if let Ok(after)=shape.paste_geometry(before,p.include_size,p.include_outline) { + if let Ok(after)=p.geometry(&shape,before) { ui.columns(2,|cols| {cols[0].label("Before");cols[0].small(bounds(before));cols[1].label("After");cols[1].small(bounds(after));}); if after.outside_on(self.layout.formats().output) {ui.colored_label(AMBER,"Outside the screen; imported coordinates will be preserved.");} } @@ -540,11 +590,11 @@ impl Editor { if reset_mapping {p.reset_mapping();} }); if !p.shapes.is_empty() { - let values=p.values(&self.layout); - let valid=values.as_ref().map_err(Clone::clone).and_then(|values| {let mut preview=self.layout.clone();preview.apply_import(values)}); + let mut preview=self.layout.clone(); + let valid=p.apply(&mut preview); if let Err(e)=&valid {ui.colored_label(AMBER,e);} - if ui.add_enabled(valid.is_ok(),egui::Button::new("Apply mapped values").fill(PURPLE)).clicked() && let Ok(values)=values { - match self.layout.apply_import(&values) {Ok(())=>{self.sync();close=true;},Err(e)=>p.error=e} + if ui.add_enabled(valid.is_ok(),egui::Button::new("Apply mapped values").fill(PURPLE)).clicked() { + match p.apply(&mut self.layout) {Ok(())=>{self.sync();close=true;},Err(e)=>p.error=e} } } if ui.button("Cancel").clicked() {close=true;} @@ -2079,6 +2129,72 @@ mod tests { assert_eq!(p.shapes.len(), 1); } #[test] + fn paste_format_position_and_zoom_are_independent_and_undo_together() { + for size in [false, true] { + for position in [false, true] { + for zoom in [false, true] { + let mut app = Editor::default(); + app.layout + .set_framing( + 1, + midra_layout::formats::Framing { + zoom: 2.0, + offset: [0.0; 2], + }, + ) + .unwrap(); + let before = *app.layout.layers(); + let formats = *app.layout.formats(); + app.open_paste("Source — visible box (device container unverified)\nHorizontal: 500 px\nVertical: 600 px\nWidth: 300 px\nHeight: 250 px\nCrop zoom: 300 %".into()); + let p = app.paste.as_mut().unwrap(); + assert!(p.error.is_empty(), "{}", p.error); + p.include_size = size; + p.include_position = position; + p.include_zoom = zoom; + let result = p.apply(&mut app.layout); + if !size && !position && !zoom { + assert!(result.unwrap_err().contains("Choose at least one")); + } else { + result.unwrap(); + let g = app.layout.layers()[1]; + assert_eq!( + [g.x, g.y], + if position { + [350.0, 475.0] + } else { + [before[1].x, before[1].y] + } + ); + assert_eq!( + [g.width, g.height], + if size { + [300.0, 250.0] + } else { + [before[1].width, before[1].height] + } + ); + assert!( + (app.layout.formats().mapping(1, g).unwrap().framing.zoom + - if zoom { 3.0 } else { 2.0 }) + .abs() + < 1e-8 + ); + app.layout.undo(); + } + assert_eq!(*app.layout.layers(), before); + assert_eq!(*app.layout.formats(), formats); + } + } + } + let mut app = Editor::default(); + app.open_paste(include_str!("../tests/fixtures/drawio-rectangle.txt").into()); + let p = app.paste.as_mut().unwrap(); + assert!(!p.zoom_available()); + p.include_size = false; + p.include_position = false; + assert!(p.apply(&mut app.layout).is_err()); + } + #[test] fn native_copy_paste_round_trip_supports_single_and_multiple_layers() { for selection in [[false, true], [true, true]] { let mut app = Editor::default(); diff --git a/crates/midra-layout/src/import.rs b/crates/midra-layout/src/import.rs index 9f696ca..d804f82 100644 --- a/crates/midra-layout/src/import.rs +++ b/crates/midra-layout/src/import.rs @@ -10,6 +10,7 @@ pub struct DetectedShape { pub outline: [f64; 2], pub background: bool, pub background_only: bool, + pub zoom: Option, } impl DetectedShape { pub fn paste_geometry( @@ -64,6 +65,7 @@ pub fn parse_values(text: &str) -> Result { outline: [s.stroke_width; 2], background: false, background_only: false, + zoom: None, }) .collect(), svg: false, @@ -78,12 +80,36 @@ fn parse_midra_values(text: &str) -> Result { .map(str::trim) .filter(|line| !line.is_empty()) .collect(); - let (blocks, remainder) = lines.as_chunks::<5>(); - if !remainder.is_empty() || blocks.is_empty() || blocks.len() > 256 { - return Err("Incomplete Midra values: each layer needs its name, Horizontal, Vertical, Width and Height (up to 256 layers).".into()); - } let mut shapes = Vec::new(); - for block in blocks { + let mut remaining = lines.as_slice(); + while !remaining.is_empty() { + if remaining.len() < 5 || shapes.len() >= 256 { + return Err("Incomplete Midra values: each layer needs its name, Horizontal, Vertical, Width and Height (up to 256 layers).".into()); + } + let (block, rest) = remaining.split_at(5); + remaining = rest; + let zoom = if remaining + .first() + .is_some_and(|line| line.starts_with("Crop zoom:")) + { + let value = remaining[0] + .strip_prefix("Crop zoom:") + .unwrap() + .trim() + .strip_suffix('%') + .ok_or("Crop zoom must be a percentage.")? + .trim() + .parse::() + .map_err(|_| "Invalid crop zoom percentage.")? + / 100.0; + if !value.is_finite() || !(1.0..=100.0).contains(&value) { + return Err("Crop zoom must be between 100% and 10000%.".into()); + } + remaining = &remaining[1..]; + Some(value) + } else { + None + }; let id = block[0] .strip_suffix(" — visible box (device container unverified)") .filter(|id| !id.is_empty()) @@ -118,12 +144,13 @@ fn parse_midra_values(text: &str) -> Result { outline: [0.0; 2], background: false, background_only: false, + zoom, }); } Ok(ImportDocument { shapes, svg: false, - note: "Midra Layout: center positions converted to top-left bounds. Copied values are rounded to whole pixels; source formats and crop settings are not copied.".into(), + note: "Midra Layout: center positions converted to top-left bounds. Copied values are rounded to whole pixels; optional crop zoom is available separately. Source formats and crop offsets are not copied.".into(), }) } @@ -426,6 +453,7 @@ fn walk( outline: [stroke * matrix.x.abs(), stroke * matrix.y.abs()], background, background_only: tag == "image", + zoom: None, }); if out.len() > 256 { return Err("Import is limited to 256 rectangles.".into()); diff --git a/crates/midra-layout/src/lib.rs b/crates/midra-layout/src/lib.rs index 4e91590..a1d465e 100644 --- a/crates/midra-layout/src/lib.rs +++ b/crates/midra-layout/src/lib.rs @@ -573,6 +573,35 @@ impl Layout { self.finish_drag(); self.commit(next) } + /// Import geometry and optional crop zoom together as one atomic edit. + pub fn apply_import_with_zoom( + &mut self, + values: &[(usize, Geometry)], + zooms: &[(usize, f64)], + ) -> Result<(), String> { + let mut draft = self.clone(); + draft.apply_import(values)?; + let mut seen = Vec::new(); + for &(i, zoom) in zooms { + if !values.iter().any(|(target, _)| *target == i) || seen.contains(&i) { + return Err("Each zoom must map to one imported layer, without duplicates.".into()); + } + seen.push(i); + let g = draft.layers[i]; + let mut framing = draft.formats.mapping(i, g)?.framing; + let (_, limits) = formats::limits(draft.formats.input(i)?, [g.width, g.height], zoom)?; + framing.zoom = zoom; + for (offset, limit) in framing.offset.iter_mut().zip(limits) { + *offset = offset.clamp(-limit, limit); + } + draft.set_framing(i, framing)?; + } + self.finish_drag(); + let before = self.snapshot(); + self.restore(draft.snapshot()); + self.remember(before); + Ok(()) + } pub fn nudge(&mut self, dx: f64, dy: f64) -> Result<(), String> { self.finish_drag(); let mut next = self.layers; diff --git a/crates/midra-layout/tests/import.rs b/crates/midra-layout/tests/import.rs index 5ccbf02..ecfb68b 100644 --- a/crates/midra-layout/tests/import.rs +++ b/crates/midra-layout/tests/import.rs @@ -209,3 +209,61 @@ fn midra_values_convert_centers_and_reject_incomplete_or_invalid_batches() { assert!(parse_values(&format!("{one}\n\n{bad}")).is_err()); } } + +#[test] +fn native_clipboard_accepts_optional_zoom_and_rejects_invalid_percentages() { + let old = "Layer — visible box (device container unverified)\nHorizontal: 100 px\nVertical: 200 px\nWidth: 100 px\nHeight: 100 px"; + let text = format!("{old}\nCrop zoom: 250 %\n\n{old}"); + let doc = parse_values(&text).unwrap(); + assert_eq!(doc.shapes[0].zoom, Some(2.5)); + assert_eq!(doc.shapes[1].zoom, None); + for value in [ + "NaN %", + "99 %", + "10001 %", + "200 px", + "200 %\nCrop zoom: 300 %", + ] { + assert!(parse_values(&format!("{old}\nCrop zoom: {value}")).is_err()); + } +} + +#[test] +fn geometry_and_zoom_import_is_atomic_and_clamps_offsets_on_zoom_out() { + let mut l = Layout::default(); + l.set_selection([true; 2]); + l.set_framing( + 1, + midra_layout::formats::Framing { + zoom: 3.0, + offset: [200.0, 100.0], + }, + ) + .unwrap(); + let before = *l.layers(); + let formats = *l.formats(); + let values = [ + ( + 0, + Geometry { + x: 99.0, + ..before[0] + }, + ), + (1, before[1]), + ]; + assert!( + l.apply_import_with_zoom(&values, &[(0, 2.0), (1, f64::NAN)]) + .is_err() + ); + assert_eq!(*l.layers(), before); + assert_eq!(*l.formats(), formats); + l.apply_import_with_zoom(&values, &[(0, 2.0), (1, 1.0)]) + .unwrap(); + let framing = l.formats().mapping(1, l.layers()[1]).unwrap().framing; + assert_eq!(framing.zoom, 1.0); + assert_eq!(framing.offset, [0.0; 2]); + l.undo(); + assert_eq!(*l.layers(), before); + assert_eq!(*l.formats(), formats); +} diff --git a/docs/midra-layout.md b/docs/midra-layout.md index 4a274f5..beefca4 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -23,9 +23,15 @@ cargo run --locked -p midra-layout mapping follows document order and the selected layer list. Every selected destination must receive exactly one rectangle: count mismatches and duplicate mappings block Apply and explain what needs changing. Nothing changes yet. -4. Leave **Include size / format** checked to import width and height along with - position, or uncheck it for position only. Choose **Include outline in bounds** - if the layer should cover the rectangle's outline too. +4. Choose independently what to paste: **Format (width / height)**, **Position**, + and **Crop zoom**. Zoom is enabled only when present in the data (new Midra + clipboard values include it; older copies, draw.io and SVG do not). All + available values are initially enabled. Unchecked values retain destination + settings; format-only paste keeps its top-left position. Choose **Include + outline in bounds** if the layer should cover the rectangle's outline too. + Zoom applies to the resulting layer size; existing crop offsets clamp if + necessary. Mixed batches keep destination zoom where the source lacks it. + At least one available value must be enabled. 5. Click **Apply mapped values** to update the entire selection in one undo step. Cancel leaves all layers unchanged. Invalid geometry blocks the whole batch, without partial changes. @@ -132,7 +138,8 @@ clipboard testing against a running draw.io instance remains to be done. the usual destination mapping and exact layer-count requirement. Center values are converted back to top-left bounds; whole-pixel export rounding still applies (an odd width/height can produce a half-pixel top-left). Source formats and crop - settings are not copied. This is not a native WebRCS clipboard payload. + offsets are not copied. Crop zoom is included separately as a percentage and + can be toggled on paste. This is not a native WebRCS clipboard payload. ## Align selected layers