From ade0c0ab1ba31045186c1bdcb7f26bd7890e650f Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Sat, 14 Nov 2026 11:47:21 +0100 Subject: [PATCH] Add Shift and Ctrl-Shift grid snapping for Midra layers --- crates/midra-layout/src/gui.rs | 196 ++++++++++++++++------ crates/midra-layout/src/preferences_ui.rs | 2 +- crates/midra-layout/src/snapping.rs | 78 ++++++++- crates/midra-layout/tests/snapping.rs | 139 +++++++++++++++ docs/interfaces/midra-layout-settings.md | 2 +- docs/midra-layout.md | 15 +- docs/midralayout/changelog.md | 2 + 7 files changed, 371 insertions(+), 63 deletions(-) diff --git a/crates/midra-layout/src/gui.rs b/crates/midra-layout/src/gui.rs index 7539fb9..5746200 100644 --- a/crates/midra-layout/src/gui.rs +++ b/crates/midra-layout/src/gui.rs @@ -1642,6 +1642,24 @@ impl Editor { } None } + fn drag_with_modifiers( + &mut self, + point: [f64; 2], + modifiers: egui::Modifiers, + scale: f32, + ) -> [Option; 2] { + if modifiers.shift && !modifiers.alt { + self.layout + .drag_to_grid(point, if modifiers.ctrl { 100.0 } else { 10.0 }) + } else { + let mut snapping = self.snapping; + if modifiers.alt { + snapping.enabled = false; + } + self.layout + .drag_to_snapped(point, snapping, 6.0 / scale as f64) + } + } fn active_resize_mode(&self) -> ResizeMode { if self.layout.selected_indices().len() < 2 { ResizeMode::Individual @@ -2013,7 +2031,7 @@ impl Editor { ) { self.layout.gesture_error = Some(e); } - } else if shift || self.layout.hit(point).is_none() { + } else if self.layout.hit(point).is_none() { let previous = self.layout.selection_mask(); let base = if shift { previous.clone() @@ -2034,13 +2052,7 @@ impl Editor { } } self.snap_guides = [None; 2]; - let mut snapping = self.snapping; - if self.layout.resizing() && ui.input(|i| i.modifiers.shift) { - snapping.enabled = !snapping.enabled; - } - if ui.input(|i| i.modifiers.alt) { - snapping.enabled = false; - } + let modifiers = ui.input(|i| i.modifiers); if response.dragged() { if self.panning { self.pan += response.drag_delta() / scale; @@ -2052,9 +2064,7 @@ impl Editor { m.end = point; self.layout.select_region(m.start, point, &m.base); } else { - self.snap_guides = - self.layout - .drag_to_snapped(point, snapping, 6.0 / scale as f64); + self.snap_guides = self.drag_with_modifiers(point, modifiers, scale); } self.sync(); } @@ -2069,8 +2079,7 @@ impl Editor { m.end = point; self.layout.select_region(m.start, point, &m.base); } else { - self.layout - .drag_to_snapped(point, snapping, 6.0 / scale as f64); + self.snap_guides = self.drag_with_modifiers(point, modifiers, scale); } self.sync(); } @@ -4158,59 +4167,136 @@ mod tests { app.layout.undo(); assert_eq!(*app.layout.layers(), before); } + fn frame_modifiers( + app: &mut Editor, + ctx: &egui::Context, + modifiers: egui::Modifiers, + mut events: Vec, + ) { + for event in &mut events { + if let egui::Event::PointerButton { + modifiers: current, .. + } = event + { + *current = modifiers; + } + } + let _ = ctx.run( + egui::RawInput { + screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(1440.0, 940.0))), + modifiers, + events, + ..Default::default() + }, + |ctx| app.ui(ctx), + ); + } #[test] - fn shift_inverts_resize_snapping_from_press_through_release() { - for enabled in [false, true] { + fn modifier_grids_move_and_resize_through_release_at_different_zoom_levels() { + for resize in [false, true] { + for enabled in [false, true] { + for (ctrl, spacing) in [(false, 10.0), (true, 100.0)] { + for zoom in [0.75, 1.0] { + let ctx = egui::Context::default(); + let mut app = Editor { + zoom, + ..Default::default() + }; + app.snapping.enabled = enabled; + let before = app.layout.layers().clone(); + let output = frame(&mut app, &ctx, vec![]); + let rect = layer_rects(&output)[1]; + let scale = rect.width() / before[1].width as f32; + let start = if resize { + rect.right_center() + } else { + rect.center() + }; + let end = start + Vec2::new(37.0, 23.0) * scale; + let modifiers = egui::Modifiers { + shift: true, + ctrl, + command: ctrl, + ..Default::default() + }; + for events in [ + vec![egui::Event::PointerMoved(start), mouse(start, true)], + vec![egui::Event::PointerMoved(end)], + vec![mouse(end, false)], + ] { + frame_modifiers(&mut app, &ctx, modifiers, events); + } + let next = app.layout.layers()[1]; + if resize { + assert!( + (next.x + next.width + - ((before[1].x + before[1].width + 37.0) / spacing).round() + * spacing) + .abs() + < 0.01 + ); + assert_eq!(next.x, before[1].x); + } else { + assert!( + (next.x - ((before[1].x + 37.0) / spacing).round() * spacing).abs() + < 0.01 + ); + assert!( + (next.y - ((before[1].y + 23.0) / spacing).round() * spacing).abs() + < 0.01 + ); + } + assert_eq!(app.layout.layers()[0], before[0]); + assert_eq!(app.snapping.enabled, enabled); + assert!(app.marquee.is_none()); + app.layout.undo(); + assert_eq!(*app.layout.layers(), before); + } + } + } + } + } + + #[test] + fn grid_release_uses_current_modifiers_and_alt_bypasses_both_grids() { + for alt in [false, true] { let ctx = egui::Context::default(); let mut app = Editor::default(); - app.snapping.enabled = enabled; - app.snapping.pixels = false; - app.snapping.layer_edges = false; + app.snapping.enabled = true; + let before = app.layout.layers().clone(); let output = frame(&mut app, &ctx, vec![]); let rect = layer_rects(&output)[1]; - let g = app.layout.layers()[1]; - let scale = rect.width() / g.width as f32; - let start = rect.right_center(); - let end = start + Vec2::new((1920.0 - g.x - g.width) as f32 * scale - 3.0, 0.0); + let scale = rect.width() / before[1].width as f32; + let start = rect.center(); + let end = start + Vec2::new(13.0, 37.0) * scale; let shift = egui::Modifiers { shift: true, ..Default::default() }; - for events in [ + frame_modifiers( + &mut app, + &ctx, + shift, vec![egui::Event::PointerMoved(start), mouse(start, true)], - vec![egui::Event::PointerMoved(end)], - vec![mouse(end, false)], - ] { - let events = events - .into_iter() - .map(|mut e| { - if let egui::Event::PointerButton { modifiers, .. } = &mut e { - *modifiers = shift; - } - e - }) - .collect(); - let _ = ctx.run( - egui::RawInput { - screen_rect: Some(Rect::from_min_size( - Pos2::ZERO, - Vec2::new(1440.0, 940.0), - )), - modifiers: shift, - events, - ..Default::default() - }, - |ctx| app.ui(ctx), - ); - } - let next = app.layout.layers()[1]; - assert!( - next.width > g.width, - "Shift must resize instead of selecting a region" ); - let expected = if enabled { 1914.0 } else { 1920.0 }; - assert!((next.x + next.width - expected).abs() < 0.01); - assert_eq!(app.snapping.enabled, enabled); + frame_modifiers(&mut app, &ctx, shift, vec![egui::Event::PointerMoved(end)]); + assert_eq!(app.layout.layers()[1].x, 1170.0); + assert_eq!(app.layout.layers()[1].y, 220.0); + frame_modifiers( + &mut app, + &ctx, + egui::Modifiers { + ctrl: true, + alt, + ..shift + }, + vec![mouse(end, false)], + ); + let g = app.layout.layers()[1]; + assert!((g.x - if alt { 1173.0 } else { 1200.0 }).abs() < 0.01); + assert!((g.y - if alt { 217.0 } else { 200.0 }).abs() < 0.01); + app.layout.undo(); + assert_eq!(*app.layout.layers(), before); } } #[test] diff --git a/crates/midra-layout/src/preferences_ui.rs b/crates/midra-layout/src/preferences_ui.rs index e12f5d3..a8e84b9 100644 --- a/crates/midra-layout/src/preferences_ui.rs +++ b/crates/midra-layout/src/preferences_ui.rs @@ -68,7 +68,7 @@ impl Editor { ui.checkbox(&mut self.snapping.screen_edges, "Screen edges"); ui.checkbox(&mut self.snapping.layer_edges, "Other visible layer edges"); }); - ui.weak("Hold Alt to bypass snapping. Numeric entry remains exact. Resize handles also snap; crop-content handles do not."); + ui.weak("Shift: 10 px grid · Ctrl+Shift: 100 px grid · Alt: bypass snapping. Applies to layer movement/resize, not numeric entry or crop-content handles."); ui.separator(); ui.label("Arrow keys: move 1 pixel · Shift-arrow: move 10 pixels"); ui.label("Shift-click: add/remove a layer from selection"); diff --git a/crates/midra-layout/src/snapping.rs b/crates/midra-layout/src/snapping.rs index 888b68d..5016c85 100644 --- a/crates/midra-layout/src/snapping.rs +++ b/crates/midra-layout/src/snapping.rs @@ -30,7 +30,7 @@ impl Layout { tolerance: f64, ) -> [Option; 2] { if self.resize.is_some() && options.enabled && tolerance.is_finite() && tolerance >= 0.0 { - return self.resize_to_snapped(point, options, tolerance); + return self.resize_to_snapped(point, options, tolerance, None); } let mut guides = [None; 2]; let Some((selected, before, start)) = self.drag.clone() else { @@ -104,14 +104,63 @@ impl Layout { } guides } + /// Snap a layer move or resize to an absolute screen-pixel grid. + /// Groups move rigidly using their bounding top-left; crop gestures bypass this grid. + pub fn drag_to_grid(&mut self, point: [f64; 2], spacing: f64) -> [Option; 2] { + if !spacing.is_finite() || spacing <= 0.0 || point.iter().any(|v| !v.is_finite()) { + return [None; 2]; + } + if self.resize.is_some() { + return self.resize_to_snapped( + point, + Snapping { + enabled: true, + pixels: true, + screen_edges: false, + layer_edges: false, + }, + 0.0, + Some(spacing), + ); + } + let Some((selected, before, start)) = self.drag.clone() else { + self.drag_to(point); + return [None; 2]; + }; + let mut origin = [f64::INFINITY; 2]; + for (i, g) in before.layers.iter().enumerate() { + if selected[i] { + origin[0] = origin[0].min(g.x); + origin[1] = origin[1].min(g.y); + } + } + let target: [f64; 2] = std::array::from_fn(|axis| { + ((origin[axis] + point[axis] - start[axis]) / spacing).round() * spacing + }); + let delta = [target[0] - origin[0], target[1] - origin[1]]; + let mut next = before.layers; + for (i, g) in next.iter_mut().enumerate() { + if selected[i] { + g.x += delta[0]; + g.y += delta[1]; + } + } + if next.iter().all(|g| g.validate().is_ok()) { + self.layers = next; + target.map(Some) + } else { + [None; 2] + } + } fn resize_to_snapped( &mut self, point: [f64; 2], options: Snapping, tolerance: f64, + grid: Option, ) -> [Option; 2] { let r = self.resize.clone().expect("resize gesture"); - self.drag_to(point); + self.drag_to_with_precision(point, grid.is_some()); if self.gesture_error.is_some() || point.iter().any(|v| !v.is_finite()) { return [None; 2]; } @@ -124,6 +173,26 @@ impl Layout { .1 }; let current = handle_point(self.layers[r.index]); + // Free corners can reach both grid axes; proportional corners choose one + // driving axis below so the fixed anchor and aspect ratio remain exact. + if let Some(spacing) = grid + && !r.keep_ratio + && matches!(r.handle, ResizeHandle::Corner(_)) + { + let targets = current.map(|v| (v / spacing).round() * spacing); + self.drag_to_with_precision( + std::array::from_fn(|axis| point[axis] + targets[axis] - current[axis]), + true, + ); + if self.gesture_error.is_some() { + self.restore(base); + return [None; 2]; + } + let reached = handle_point(self.layers[r.index]); + return std::array::from_fn(|axis| { + ((reached[axis] - targets[axis]).abs() < 1e-6).then_some(targets[axis]) + }); + } let mut candidates = Vec::new(); for (axis, _) in current.iter().enumerate() { if (axis == 0 && matches!(r.handle, ResizeHandle::Top | ResizeHandle::Bottom)) @@ -158,7 +227,8 @@ impl Layout { candidates.push((0, (target - current[axis]).abs(), axis, target)); } if options.pixels { - let target = current[axis].round(); + let spacing = grid.unwrap_or(1.0); + let target = (current[axis] / spacing).round() * spacing; candidates.push((1, (target - current[axis]).abs(), axis, target)); } } @@ -184,7 +254,7 @@ impl Layout { && (handle_point(self.layers[r.index])[axis] - target).abs() < 1e-6 { let mut guides = [None; 2]; - if priority == 0 { + if priority == 0 || grid.is_some() { guides[axis] = Some(target); } return guides; diff --git a/crates/midra-layout/tests/snapping.rs b/crates/midra-layout/tests/snapping.rs index 1120623..2fc3f69 100644 --- a/crates/midra-layout/tests/snapping.rs +++ b/crates/midra-layout/tests/snapping.rs @@ -211,3 +211,142 @@ fn ratio_locked_corners_reach_fractional_layer_edges() { assert!((next.width / next.height - g.width / g.height).abs() < 1e-9); } } + +#[test] +fn grid_movement_uses_group_bounds_and_preserves_fractional_spacing() { + for spacing in [10.0, 100.0] { + let mut layout = Layout::default(); + let mut g = layout.layers()[0]; + g.x = -123.25; + g.y = -17.5; + layout.apply(0, g).unwrap(); + layout.set_selection([true; 2]); + let before = layout.layers().clone(); + let formats = layout.formats().clone(); + layout.start_drag([1200.0, 200.0]); + let guides = layout.drag_to_grid([1207.0, 203.0], spacing); + let x = ((g.x + 7.0) / spacing).round() * spacing; + let y = ((g.y + 3.0) / spacing).round() * spacing; + assert_eq!(guides, [Some(x), Some(y)]); + assert_eq!(layout.layers()[0].x, x); + assert_eq!( + layout.layers()[1].x - layout.layers()[0].x, + before[1].x - before[0].x + ); + assert_eq!(*layout.formats(), formats); + layout.finish_drag(); + layout.undo(); + assert_eq!(*layout.layers(), before); + } +} + +#[test] +fn grid_resize_respects_anchors_ratios_and_free_corner_axes() { + use midra_layout::ResizeHandle; + for spacing in [10.0, 100.0] { + for keep_ratio in [false, true] { + let mut layout = Layout::default(); + layout.select(Some(0)); + let mut g = layout.layers()[0]; + g.x = 123.25; + g.y = 181.5; + layout.apply(0, g).unwrap(); + for (handle, start) in ResizeHandle::positions(g) { + layout.start_handle_resize(0, handle, start, keep_ratio); + let guides = layout.drag_to_grid([start[0] + 37.0, start[1] + 23.0], spacing); + let next = layout.layers()[0]; + let positions = ResizeHandle::positions(next); + let actual = positions.iter().find(|(h, _)| *h == handle).unwrap().1; + let anchor = positions + .iter() + .find(|(h, _)| *h == handle.opposite()) + .unwrap() + .1; + let original_anchor = ResizeHandle::positions(g) + .into_iter() + .find(|(h, _)| *h == handle.opposite()) + .unwrap() + .1; + for axis in 0..2 { + assert!((anchor[axis] - original_anchor[axis]).abs() < 1e-8); + } + assert!(guides.iter().any(Option::is_some)); + for axis in 0..2 { + if let Some(target) = guides[axis] { + assert!((actual[axis] - target).abs() < 1e-8); + assert!((target / spacing - (target / spacing).round()).abs() < 1e-8); + } + } + if keep_ratio { + assert!((next.width / next.height - g.width / g.height).abs() < 1e-8); + } else if matches!(handle, ResizeHandle::Corner(_)) { + assert!(guides.iter().all(Option::is_some)); + } + layout.cancel_drag(); + assert_eq!(layout.layers()[0], g); + } + } + } +} + +#[test] +fn grid_group_resize_keeps_mirror_and_opposite_relationships() { + use midra_layout::{ResizeHandle, ResizeMode}; + for mode in [ResizeMode::Same, ResizeMode::Mirror, ResizeMode::Opposite] { + let mut layout = Layout::default(); + layout.set_selection([true; 2]); + let before = layout.layers().clone(); + layout + .start_selected_resize(0, ResizeHandle::Right, [760.0, 360.0], true, mode) + .unwrap(); + assert_eq!( + layout.drag_to_grid([837.0, 360.0], 100.0), + [Some(800.0), None] + ); + assert_eq!(layout.layers()[0].width, 680.0); + assert_eq!(layout.layers()[1].width, 680.0); + if mode == ResizeMode::Same { + assert_eq!(layout.layers()[1].x, before[1].x); + } else { + assert_eq!( + layout.layers()[1].x + layout.layers()[1].width, + before[1].x + before[1].width + ); + } + layout.finish_drag(); + layout.undo(); + assert_eq!(*layout.layers(), before); + } +} + +#[test] +fn grid_ignores_crop_content_and_invalid_spacing_does_not_edit() { + use midra_layout::formats::Framing; + let mut layout = Layout::default(); + layout + .set_framing( + 1, + Framing { + zoom: 2.0, + offset: [0.0; 2], + }, + ) + .unwrap(); + let geometry = layout.layers().clone(); + layout.start_content_drag(1, [1200.0, 200.0]); + assert_eq!(layout.drag_to_grid([1207.5, 203.5], 100.0), [None; 2]); + let framing = layout + .formats() + .mapping(1, layout.layers()[1]) + .unwrap() + .framing; + assert!((framing.offset[0] - 7.5).abs() < 1e-8); + assert!((framing.offset[1] - 3.5).abs() < 1e-8); + assert_eq!(*layout.layers(), geometry); + layout.cancel_drag(); + layout.start_drag([1200.0, 200.0]); + for spacing in [0.0, -10.0, f64::INFINITY, f64::NAN] { + assert_eq!(layout.drag_to_grid([1300.0, 300.0], spacing), [None; 2]); + assert_eq!(*layout.layers(), geometry); + } +} diff --git a/docs/interfaces/midra-layout-settings.md b/docs/interfaces/midra-layout-settings.md index fad64a5..1d6c1cf 100644 --- a/docs/interfaces/midra-layout-settings.md +++ b/docs/interfaces/midra-layout-settings.md @@ -105,7 +105,7 @@ fixed six-logical-pixel proximity radius converted by viewport scale. It affects layer movement and resize handles; numeric entry, nudges and crop-content gestures bypass it. Resize snapping preserves anchors and proportions and shows guides only when the resulting edge actually reaches its target. -Shift temporarily inverts snapping during layer resizing, including release, without changing the saved option. Alt temporarily disables it and takes precedence over Shift. +Shift temporarily overrides snapping with a 10-screen-pixel grid for layer movement and resizing; Ctrl+Shift uses 100 pixels. Alt bypasses both grids and ordinary snapping, including on release. These modifiers do not change the saved options or settings version. **Preferences → Midra integration → Allow sending to Program** saves immediately. Restore default preferences disables it. Projects do not override this application preference; the Preview/Program destination itself remains session-only. diff --git a/docs/midra-layout.md b/docs/midra-layout.md index 5fd89e7..0f872e5 100644 --- a/docs/midra-layout.md +++ b/docs/midra-layout.md @@ -116,7 +116,7 @@ clipboard testing against a running draw.io instance remains to be done. 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, + it intersects, in either drag direction. **Shift-drag on empty canvas** 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 @@ -657,7 +657,18 @@ no layer mapping. Layer rows use padlock and eye icon buttons for locking and visibility, with tooltips and highlighted locked/hidden states. Double-click a layer name in the right-hand list to rename it. Enter saves, Escape or Cancel discards the edit; names must contain 1–128 characters. Renaming preserves the layer ID and folder and supports Undo. -Snapping also applies to side and corner resizing, including with aspect ratio locked. Hold **Shift** during a resize to temporarily invert snapping (on when disabled, off when enabled); release uses the current modifier state. **Alt** still disables snapping. Shift-drag on a resize handle resizes; Shift-click and Shift-drag elsewhere retain selection behavior. +Hold **Shift** while moving or resizing layers to snap to a **10 px grid**; +**Ctrl+Shift** uses a **100 px grid**. These temporary grids override ordinary +pixel/edge snapping, even when snapping is disabled in Preferences. **Alt** +bypasses both. The modifier state on release determines the final position. +Grid coordinates are screen pixels measured from the screen's top-left, independent +of viewport zoom. Group movement snaps the selection's bounding top-left and keeps +relative spacing. Resize snapping keeps opposite anchors and group proportions; +free corners snap both axes, while ratio-locked corners snap one driving axis. +Cyan guides mark reached grid lines. Numeric entry, crop-content gestures and camera +panning are unaffected. Shift-click still toggles selection; Shift-drag on a layer +moves it on the grid, and Shift-drag on empty canvas adds a selection box. +This replaces the previous Shift-to-invert-resize-snapping shortcut. Midra layer lists omit unassigned source slots (`NONE` or empty). Assigned inputs remain listed even if the layer is off. The exporter defaults to Preview and hides Program until **Preferences → Midra integration → Allow sending to Program** is checked. This preference is saved automatically; turning it off returns the exporter and quick Apply action to Preview. diff --git a/docs/midralayout/changelog.md b/docs/midralayout/changelog.md index f5bcd59..372c371 100644 --- a/docs/midralayout/changelog.md +++ b/docs/midralayout/changelog.md @@ -4,6 +4,8 @@ ## Unreleased +- Shift-drag moves/resizes on a 10 px grid; Ctrl+Shift uses 100 px, Alt bypasses. Replaces resize snap inversion; Shift-click and empty-canvas additive selection remain. + - Add a subtle “Double-click to edit” reminder in the layer-list header. - Backlog: capture still input previews from Midra; verify on-demand/continuous preview access and firmware support.