From 7e9f7174a9631a2aed4ddd7453bb5e3204324ebc Mon Sep 17 00:00:00 2001 From: Praveen Vikram Date: Wed, 11 Nov 2026 00:21:11 -0500 Subject: [PATCH] add equidistant noed guidelines --- src/canvas/mod.rs | 47 ++++++--- src/canvas/paint.rs | 60 ++++++++++- src/canvas/tests.rs | 133 +++++++++++++++++++++++- src/snap/mod.rs | 242 ++++++++++++++++++++++++++++++++++++++++++-- src/snap/tests.rs | 195 +++++++++++++++++++++++++++++++++++ 5 files changed, 652 insertions(+), 25 deletions(-) diff --git a/src/canvas/mod.rs b/src/canvas/mod.rs index 06a5806..df54159 100644 --- a/src/canvas/mod.rs +++ b/src/canvas/mod.rs @@ -24,7 +24,7 @@ use crate::document::{self, EdgeEnd, Item, LabelRef}; use crate::history::Document; use crate::scene::SceneEdge; use crate::selection::Selection; -use crate::snap::{Axis, Feature, Guide, Side, Targets}; +use crate::snap::{Axis, EqualGaps, Feature, Guide, Side, Targets}; use crate::style::Style; use crate::text_field::{self, End}; use crate::tool::{NodeShape, Tool}; @@ -61,6 +61,12 @@ const HANDLE_SIZE: f32 = 7.0; const GUIDE: Color32 = Color32::from_rgb(0xE6, 0x00, 0x8A); /// How far guides reach past what they span, in screen points. const GUIDE_OVERHANG: f32 = 8.0; +/// How far above a row's highest node, or left of a column's leftmost, the +/// dimension lines showing equal gaps are, in screen points. +const DIMENSION_OFFSET: f32 = 20.0; +/// How long the arrowheads of dimension lines are along and across them, in +/// screen points, and how far the lines up to them reach past. +const ARROWHEAD: f32 = 5.0; /// The sides and corners of the selected node that can be dragged, e.g. /// `RIGHT_CENTER` for its right side. @@ -138,6 +144,8 @@ pub struct Canvas { snapping: bool, /// What this frame's drag lines up with. guides: Vec, + /// The equal gaps this frame's move makes. + equal_gaps: Vec, } /// Where the graph shows on the canvas. @@ -307,6 +315,7 @@ impl Canvas { // Alt skips snapping, e.g. to place a node just beside a line. self.snapping = self.options.snap_lines && !ui.input(|input| input.modifiers.alt); self.guides.clear(); + self.equal_gaps.clear(); // A shortcut can switch tools mid-drag, which drops the shape. self.shape_drag.take_if(|drag| drag.tool != tool); self.edge_draw.take_if(|draw| draw.tool != tool); @@ -1120,13 +1129,13 @@ impl Canvas { let to_graph = |pos: Pos2| graph_point(shown.to_screen, pos); if !canvas.drag_stopped() { let to = canvas.interact_pointer_pos().map(to_graph)?; - let (delta, guides) = self.snap_move(shown, selected, to - drag.from); - self.guides = guides; + let (delta, guides, gaps) = self.snap_move(shown, selected, to - drag.from); + (self.guides, self.equal_gaps) = (guides, gaps); return Some(delta); } self.move_drag = None; if let Some(to) = ui.input(primary_release).map(to_graph) { - let ([dx, dy], _) = self.snap_move(shown, selected, to - drag.from); + let ([dx, dy], ..) = self.snap_move(shown, selected, to - drag.from); // Ending where it started changes nothing. if dx != 0.0 || dy != 0.0 { document::move_items(doc.graphml_mut(), selected.items(), dx, dy); @@ -1137,23 +1146,32 @@ impl Canvas { /// How far right and down to move the `selected` nodes for a drag by /// `delta`, in graph points, so that one lines up with a node left in - /// place, with the guides showing what lines up. With no nodes selected, - /// the selected edges' bends line up instead. - fn snap_move(&self, shown: Shown, selected: &Selection, delta: Vec2) -> ([f64; 2], Vec) { + /// place, or they make equal gaps with nodes beside them, with the guides + /// and gaps showing it. With no nodes selected, the selected edges' bends + /// line up instead. + fn snap_move( + &self, + shown: Shown, + selected: &Selection, + delta: Vec2, + ) -> ([f64; 2], Vec, Vec) { let mut delta = [delta.x, delta.y].map(f64::from); let scene = shown.scene; let moving = |node: usize| selected.contains_node(&scene.nodes[node].id); let Some(targets) = self.targets(shown, moving) else { - return (delta, Vec::new()); + return (delta, Vec::new(), Vec::new()); }; let features = |[dx, dy]: [f64; 2]| { let nodes = (0..scene.nodes.len()).filter(|&node| moving(node) && shown.is_drawn(node)); - let lines = nodes.flat_map(|node| { + let moved = nodes.map(|node| { let mut rect = shown.geometry(node); (rect.x, rect.y) = (rect.x + dx, rect.y + dy); - Feature::box_lines(&rect) + rect }); - let mut features: Vec<_> = lines.collect(); + let rects: Vec<_> = moved.collect(); + let mut features: Vec<_> = rects.iter().flat_map(Feature::box_lines).collect(); + // The gaps are those of the selection as a whole. + features.extend(Feature::block(&rects)); if features.is_empty() { let edges = (scene.edges.iter()).filter(|edge| selected.contains_edge(edge.index)); let bends = edges.flat_map(|edge| edge.graphics.path.points.iter()); @@ -1169,7 +1187,12 @@ impl Canvas { for (delta, shift) in delta.iter_mut().zip(shift) { *delta += shift.unwrap_or_default(); } - (delta, targets.guides(&features(delta))) + let features = features(delta); + ( + delta, + targets.guides(&features), + targets.equal_gaps(&features), + ) } /// Selects the nodes inside the box that a drag [`Self::start_drag`] diff --git a/src/canvas/paint.rs b/src/canvas/paint.rs index 65bfb6c..de6429f 100644 --- a/src/canvas/paint.rs +++ b/src/canvas/paint.rs @@ -17,16 +17,16 @@ use crate::document::Item; use crate::fonts; use crate::line_type; use crate::selection::Selection; -use crate::snap::{Axis, Guide}; +use crate::snap::{Axis, EqualGaps, Guide}; use crate::style::Style; use crate::svg_image::SvgImage; use super::shown::{Anchor, EdgeLook, Outline, Shown, egui_rect, shape}; use super::textures::Textures; use super::{ - BACKGROUND, Canvas, EdgeDrag, EdgePart, GUIDE, GUIDE_OVERHANG, HALO, HANDLE_SIZE, - LABEL_PADDING, MAX_TEXT_PIXELS, Owner, Preview, SELECTION, SELECTION_BOX_FILL, SELECTION_GAP, - edge, grid, + ARROWHEAD, BACKGROUND, Canvas, DIMENSION_OFFSET, EdgeDrag, EdgePart, GUIDE, GUIDE_OVERHANG, + HALO, HANDLE_SIZE, LABEL_PADDING, MAX_TEXT_PIXELS, Owner, Preview, SELECTION, + SELECTION_BOX_FILL, SELECTION_GAP, edge, grid, }; impl Canvas { @@ -118,6 +118,7 @@ impl Canvas { painter.rect_stroke(outline, 0.0, SELECTION, StrokeKind::Outside); } paint_guides(painter, shown.to_screen, &self.guides); + paint_equal_gaps(painter, shown.to_screen, &self.equal_gaps); if kept && let Some(index) = selected_edge && let Some(edge) = scene.edge(index) @@ -397,6 +398,57 @@ fn paint_guides(painter: &Painter, to_screen: TSTransform, guides: &[Guide]) { painter.add(mesh); } +/// Paints `runs` of equal gaps as yEd's dimension lines, a pixel wide: a line +/// with arrowheads across each gap, a little above the run's highest node (or +/// left of a column's leftmost), and lines from just past it along the sides +/// facing the gap, down to the middle of the band the run overlaps. +fn paint_equal_gaps(painter: &Painter, to_screen: TSTransform, runs: &[EqualGaps]) { + if runs.is_empty() { + return; + } + let pixels_per_point = painter.pixels_per_point(); + // Diagonal, so a little wider than the lines to look as strong. + let stroke = Stroke::new(1.5 / pixels_per_point, GUIDE); + let mut mesh = Mesh::default(); + for run in runs { + // Screen coordinates along the run's axis and across it. + let along = run.axis as usize; + let across = 1 - along; + let screen = + |at: f64, index: usize| to_screen.translation[index] + to_screen.scaling * at as f32; + let pos = |along_at: f32, across_at: f32| match run.axis { + Axis::X => pos2(along_at, across_at), + Axis::Y => pos2(across_at, along_at), + }; + let rect = |along_at: Rangef, across_at: Rangef| match run.axis { + Axis::X => Rect::from_x_y_ranges(along_at, across_at), + Axis::Y => Rect::from_x_y_ranges(across_at, along_at), + }; + let middle = screen((run.band[0] + run.band[1]) / 2.0, across); + let level = pixel( + screen(run.start, across) - DIMENSION_OFFSET, + pixels_per_point, + ); + for gap in &run.gaps { + let ends = gap.map(|at| pixel(screen(at, along), pixels_per_point)); + let extension = Rangef::new(level.min - ARROWHEAD, middle); + for end in ends { + mesh.add_colored_rect(rect(end, extension), GUIDE); + } + let line = Rangef::new(ends[0].min, ends[1].max); + mesh.add_colored_rect(rect(line, level), GUIDE); + let [from, to] = ends.map(|end| end.center()); + let length = ARROWHEAD.min((to - from) / 2.0); + for (tip, back) in [(from, length), (to, -length)] { + let wing = |side: f32| pos(tip + back, level.center() + side * length); + let points = vec![wing(-1.0), pos(tip, level.center()), wing(1.0)]; + painter.add(PathShape::line(points, stroke)); + } + } + } + painter.add(mesh); +} + /// The pixel a line a pixel wide at `at` on screen is drawn on, as egui puts /// a 1 px border there. pub(super) fn pixel(at: f32, pixels_per_point: f32) -> Rangef { diff --git a/src/canvas/tests.rs b/src/canvas/tests.rs index 8665ec8..e36059b 100644 --- a/src/canvas/tests.rs +++ b/src/canvas/tests.rs @@ -3490,12 +3490,26 @@ fn guides(shapes: &[Shape]) -> Vec { /// Drags the node in [`NODE`], selected, by `by`, returning what the last /// frame before the release painted. fn drag_node_by(harness: &mut Harness, by: Vec2) -> Vec { - let from = NODE.center().to_vec2(); + drag_by(harness, NODE.center(), by) +} + +/// Drags from `from` by `by`, returning what the last frame before the +/// release painted. +fn drag_by(harness: &mut Harness, from: Pos2, by: Vec2) -> Vec { + let from = from.to_vec2(); let held = harness.drag_and_hold(from, from + by); harness.frame(vec![button(harness.origin + from + by, false)]); held } +/// Adds the boxes in [`NODE`] and [`OTHER`], and a third 50 wide below the +/// gap between them, which it selects. +fn add_three_boxes(harness: &mut Harness) { + harness.add_two_boxes(); + let node = harness.add_box(pos2(300.0, 300.0), pos2(350.0, 340.0)); + harness.selected = Selection::node(node); +} + #[test] fn moved_nodes_snap_into_line_with_other_nodes() { let mut harness = Harness::new(Tool::Cursor); @@ -3523,6 +3537,123 @@ fn guides_show_what_the_moved_node_lines_up_with() { assert_eq!(guides(&harness.frame(vec![])), []); } +#[test] +fn moved_nodes_snap_halfway_between_the_nodes_beside_them() { + let mut harness = Harness::new(Tool::Cursor); + add_three_boxes(&mut harness); + // Up into the gap, 3 right of halfway. + drag_by(&mut harness, pos2(325.0, 320.0), vec2(3.0, -240.0)); + assert_eq!(harness.boxes()[2], geometry(300.0, 60.0, 50.0, 40.0)); +} + +#[test] +fn equal_gaps_show_as_dimension_lines_above_the_row() { + let mut harness = Harness::new(Tool::Cursor); + add_three_boxes(&mut harness); + let held = drag_by(&mut harness, pos2(325.0, 320.0), vec2(3.0, -240.0)); + let origin = harness.origin.to_vec2(); + // Up each side facing a gap from the middle of what the boxes all span + // across, to past a line 20 above the highest, a pixel wide. + let side = |x: f32| Rect::from_min_max(pos2(x, 25.0), pos2(x + 1.0, 80.0)).translate(origin); + let line = |from: f32, to: f32| { + Rect::from_min_max(pos2(from, 30.0), pos2(to + 1.0, 31.0)).translate(origin) + }; + assert_eq!( + guides(&held), + [ + side(250.0), + side(300.0), + line(250.0, 300.0), + side(350.0), + side(400.0), + line(350.0, 400.0), + ] + ); + // Arrowheads, wing to tip to wing, pointing out at both ends of each line. + let arrowhead = |tip: f32, back: f32| { + let points = [(tip + back, 25.5), (tip, 30.5), (tip + back, 35.5)]; + (points.iter()) + .map(|&(x, y)| pos2(x, y) + origin) + .collect::>() + }; + assert_eq!( + lines(&held, GUIDE), + [ + arrowhead(250.5, 5.0), + arrowhead(300.5, -5.0), + arrowhead(350.5, 5.0), + arrowhead(400.5, -5.0), + ] + ); + let released = harness.frame(vec![]); + assert_eq!( + (guides(&released), lines(&released, GUIDE)), + (vec![], vec![]) + ); +} + +#[test] +fn moved_nodes_snap_as_far_past_a_node_as_it_is_past_the_next() { + let mut harness = Harness::new(Tool::Cursor); + harness.add_two_boxes(); + let node = harness.add_box(pos2(600.0, 300.0), pos2(700.0, 340.0)); + harness.selected = Selection::node(node); + // 150 right of the second box, as it is of the first, and 4 more. + drag_by(&mut harness, pos2(650.0, 320.0), vec2(104.0, -240.0)); + assert_eq!(harness.boxes()[2], geometry(700.0, 60.0, 100.0, 40.0)); +} + +#[test] +fn equal_gaps_in_a_column_show_left_of_it() { + let mut harness = Harness::new(Tool::Cursor); + harness.add_box(NODE.min, NODE.max); + harness.add_box(pos2(100.0, 330.0), pos2(250.0, 410.0)); + let node = harness.add_box(pos2(400.0, 400.0), pos2(440.0, 440.0)); + harness.selected = Selection::node(node); + // Between the two boxes, 3 below halfway. + let held = drag_by(&mut harness, pos2(420.0, 420.0), vec2(-290.0, -187.0)); + assert_eq!(harness.boxes()[2], geometry(110.0, 210.0, 40.0, 40.0)); + let origin = harness.origin.to_vec2(); + let side = |y: f32| Rect::from_min_max(pos2(75.0, y), pos2(130.0, y + 1.0)).translate(origin); + let line = |from: f32, to: f32| { + Rect::from_min_max(pos2(80.0, from), pos2(81.0, to + 1.0)).translate(origin) + }; + assert_eq!( + guides(&held), + [ + side(130.0), + side(210.0), + line(130.0, 210.0), + side(250.0), + side(330.0), + line(250.0, 330.0), + ] + ); +} + +#[test] +fn a_moved_selection_snaps_into_equal_gaps_as_one() { + let mut harness = Harness::new(Tool::Cursor); + harness.add_two_boxes(); + let first = harness.add_box(pos2(300.0, 300.0), pos2(320.0, 340.0)); + let second = harness.add_box(pos2(330.0, 300.0), pos2(350.0, 340.0)); + harness.selected = Selection::of([Item::Node(first), Item::Node(second)]); + drag_by(&mut harness, pos2(310.0, 320.0), vec2(3.0, -240.0)); + let boxes = harness.boxes(); + assert_eq!((boxes[2].x, boxes[3].x), (300.0, 330.0)); +} + +#[test] +fn alt_skips_equal_gaps_too() { + let mut harness = Harness::new(Tool::Cursor); + add_three_boxes(&mut harness); + let held = harness.holding(Modifiers::ALT, |harness| { + drag_by(harness, pos2(325.0, 320.0), vec2(3.0, -240.0)) + }); + assert_eq!((guides(&held), lines(&held, GUIDE)), (vec![], vec![])); + assert_eq!(harness.boxes()[2], geometry(303.0, 60.0, 50.0, 40.0)); +} + #[test] fn moved_nodes_touch_the_nodes_beside_them() { let mut harness = Harness::new(Tool::Cursor); diff --git a/src/snap/mod.rs b/src/snap/mod.rs index 5e900d1..b109b2d 100644 --- a/src/snap/mod.rs +++ b/src/snap/mod.rs @@ -1,5 +1,6 @@ -//! Snapping what the canvas drags into line with the nodes around it, as -//! yEd's snap lines do, and the guides showing what it lines up with. +//! Snapping what the canvas drags into line with the nodes around it, or +//! into equal gaps with them, as yEd's snap lines do, and the guides showing +//! what it lines up with. use graphml::yed::{Point, Rect}; @@ -41,11 +42,12 @@ impl Side { const ALL: [Side; 3] = [Side::Start, Side::Middle, Side::End]; } -/// A line of something dragged, which may snap onto lines of what's around. +/// A line of something dragged, which may snap onto lines of what's around, +/// or the whole of it along an axis, which may snap into equal gaps. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Feature { axis: Axis, - /// Where it crosses its axis. + /// Where it crosses its axis, or where a block starts along it. at: f64, kind: Kind, /// What it spans along the other axis. @@ -59,6 +61,10 @@ enum Kind { Box(Side), /// A point, which snaps onto any side or middle, and onto the points. Point, + /// A block ending at `end`, which snaps halfway between the nearest nodes + /// either side of it, or as far past the nearest as that is past the + /// next, as yEd does. + Block { end: f64 }, } impl Feature { @@ -86,6 +92,35 @@ impl Feature { span: [coordinate(point, axis.other()); 2], }) } + + /// The box around `rects` as one block along each axis, none without + /// `rects`. + pub fn block(rects: &[Rect]) -> Vec { + let around = |axis: Axis| { + let spans = rects.iter().map(|rect| span(rect, axis)); + spans.reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])]) + }; + let blocks = Axis::BOTH.into_iter().filter_map(|axis| { + let [at, end] = around(axis)?; + let span = around(axis.other())?; + let kind = Kind::Block { end }; + Some(Feature { + axis, + at, + kind, + span, + }) + }); + blocks.collect() + } + + fn moved(mut self, by: f64) -> Feature { + self.at += by; + if let Kind::Block { end } = &mut self.kind { + *end += by; + } + self + } } /// A line drawn to show that dragged things line up along it: across `axis` @@ -98,8 +133,40 @@ pub struct Guide { pub to: f64, } -/// What dragged things snap onto: the sides and middles of nodes, and -/// points, such as the neighbours of a dragged bend. +/// Equal gaps between things side by side along `axis`, which yEd shows +/// with dimension lines: each from where one thing ends to where the next +/// starts along the axis, in graph points. All the things overlap `band` +/// across the axis, and `start` is the least coordinate across it any has, +/// such as the top of the highest in a row. +#[derive(Clone, Debug, PartialEq)] +pub struct EqualGaps { + pub axis: Axis, + pub gaps: Vec<[f64; 2]>, + pub band: [f64; 2], + pub start: f64, +} + +impl EqualGaps { + /// Adds the gap from `from` to `node`, `way` of it, if it's as wide as + /// the others and `node` overlaps the band, returning whether it did. + fn take(&mut self, from: &Extent, node: &Extent, way: Way) -> bool { + let gap = from.gap_to(node, way); + let as_wide = |other: &[f64; 2]| (length(gap) - length(*other)).abs() <= SAME; + let fits = length(gap) > SAME && self.gaps.first().is_none_or(as_wide); + match overlap(self.band, node.across) { + Some(band) if fits => { + self.band = band; + self.start = self.start.min(node.across[0]); + self.gaps.push(gap); + true + } + _ => false, + } + } +} + +/// What dragged things snap onto: the sides and middles of nodes, the gaps +/// between nodes, and points, such as the neighbours of a dragged bend. #[derive(Clone, Debug)] pub struct Targets { /// The nodes' bounds, and whether their sides count, besides their @@ -135,17 +202,25 @@ impl Targets { } /// How far to move along each axis for the nearest of `features` within - /// reach to snap onto a line it may snap onto, if any is within reach. + /// reach to snap onto a line, or into equal gaps, if any is within reach. pub fn snap(&self, features: &[Feature]) -> [Option; 2] { Axis::BOTH.map(|axis| { let along = features.iter().filter(|feature| feature.axis == axis); along - .flat_map(|feature| self.lines(feature).map(|(at, _)| at - feature.at)) + .flat_map(|feature| self.shifts(feature)) .filter(|shift| shift.abs() <= self.reach) .min_by(|a, b| a.abs().total_cmp(&b.abs())) }) } + /// The equal gaps that the blocks of `features` make with the nodes + /// beside them. + pub fn equal_gaps(&self, features: &[Feature]) -> Vec { + (features.iter()) + .flat_map(|feature| self.equal_gaps_of(feature)) + .collect() + } + /// The guides along the lines that `features` lie on, each spanning the /// features and what they line up with. pub fn guides(&self, features: &[Feature]) -> Vec { @@ -189,6 +264,7 @@ impl Targets { own == side || beside && own != Side::Middle && side != Side::Middle } Kind::Point => sides || side == Side::Middle, + Kind::Block { .. } => false, }; snaps.then(|| (line(&rect, axis, side), across)) }) @@ -201,6 +277,156 @@ impl Targets { }); nodes.chain(points) } + + /// How far `feature` may move along its axis to snap. + fn shifts(&self, feature: &Feature) -> Vec { + if !matches!(feature.kind, Kind::Block { .. }) { + return self.lines(feature).map(|(at, _)| at - feature.at).collect(); + } + // Moving may bring other nodes beside it, so it has to end up in + // equal gaps. + let spaced = |shift: &f64| { + shift.abs() <= self.reach && !self.equal_gaps_of(&feature.moved(*shift)).is_empty() + }; + self.spacing_shifts(feature) + .into_iter() + .filter(spaced) + .collect() + } + + /// How far `block` would move along its axis to be halfway between the + /// nearest nodes either side of it, or as far past the nearest as that + /// is past the next. + fn spacing_shifts(&self, block: &Feature) -> Vec { + let Some(me) = Extent::of(block) else { + return Vec::new(); + }; + let row = self.row(block.axis, &me); + let before = nearest(&row, &me, Way::Before); + let after = nearest(&row, &me, Way::After); + let mut shifts = Vec::new(); + if let (Some((_, left)), Some((_, right))) = (before, after) { + shifts.push((length(right) - length(left)) / 2.0); + } + for (way, next) in [(Way::Before, before), (Way::After, after)] { + if let Some((node, gap)) = next + && let Some((_, wanted)) = nearest(&row, &node, way) + { + let wider = length(wanted) - length(gap); + shifts.push(if way == Way::Before { wider } else { -wider }); + } + } + shifts + } + + /// The equal gaps `block` makes with the nodes beside it along its axis, + /// on along them while the gaps stay equal: one run through it if it's + /// halfway between two, else a run each way with at least two gaps. + fn equal_gaps_of(&self, block: &Feature) -> Vec { + let Some(me) = Extent::of(block) else { + return Vec::new(); + }; + let row = self.row(block.axis, &me); + let new = || EqualGaps { + axis: block.axis, + gaps: Vec::new(), + band: me.across, + start: me.across[0], + }; + let go_on = |run: &mut EqualGaps, mut from: Extent, way: Way| { + while let Some((node, _)) = nearest(&row, &from, way) + && run.take(&from, &node, way) + { + from = node; + } + }; + let mut runs = Vec::new(); + let mut halfway = new(); + if let Some((left, _)) = nearest(&row, &me, Way::Before) + && let Some((right, _)) = nearest(&row, &me, Way::After) + && halfway.take(&me, &left, Way::Before) + && halfway.take(&me, &right, Way::After) + { + go_on(&mut halfway, left, Way::Before); + go_on(&mut halfway, right, Way::After); + runs.push(halfway); + } else { + for way in [Way::Before, Way::After] { + let mut run = new(); + go_on(&mut run, me, way); + if run.gaps.len() >= 2 { + runs.push(run); + } + } + } + for run in &mut runs { + run.gaps.sort_by(|a, b| a[0].total_cmp(&b[0])); + } + runs + } + + /// The nodes beside `block` along `axis`: those overlapping it across. + fn row(&self, axis: Axis, block: &Extent) -> Vec { + let nodes = self.nodes.iter().filter(|(_, sides)| *sides); + let extents = nodes.map(|(rect, _)| Extent { + along: span(rect, axis), + across: span(rect, axis.other()), + }); + let beside = |node: &Extent| overlap(node.across, block.across).is_some(); + extents.filter(beside).collect() + } +} + +/// What a node or block spans along an axis and across it. +#[derive(Clone, Copy, Debug)] +struct Extent { + along: [f64; 2], + across: [f64; 2], +} + +impl Extent { + fn of(block: &Feature) -> Option { + match block.kind { + Kind::Block { end } => Some(Extent { + along: [block.at, end], + across: block.span, + }), + _ => None, + } + } + + /// The gap along the axis from it to `other`, `way` of it. + fn gap_to(&self, other: &Extent, way: Way) -> [f64; 2] { + match way { + Way::Before => [other.along[1], self.along[0]], + Way::After => [self.along[1], other.along[0]], + } + } +} + +/// Towards the start of an axis, or its end. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Way { + Before, + After, +} + +/// The node of `row` nearest `from` of those wholly `way` of it, with the +/// gap between them. +fn nearest(row: &[Extent], from: &Extent, way: Way) -> Option<(Extent, [f64; 2])> { + let gaps = row.iter().map(|node| (*node, from.gap_to(node, way))); + gaps.filter(|(_, gap)| length(*gap) >= -SAME) + .min_by(|(_, a), (_, b)| length(*a).total_cmp(&length(*b))) +} + +/// Where `a` and `b` overlap, if by more than [`SAME`]. +fn overlap(a: [f64; 2], b: [f64; 2]) -> Option<[f64; 2]> { + let both = [a[0].max(b[0]), a[1].min(b[1])]; + (length(both) > SAME).then_some(both) +} + +fn length([start, end]: [f64; 2]) -> f64 { + end - start } /// Where the `side` of `rect` crosses `axis`. Its middle is where the canvas diff --git a/src/snap/tests.rs b/src/snap/tests.rs index e8d214a..23002fd 100644 --- a/src/snap/tests.rs +++ b/src/snap/tests.rs @@ -196,6 +196,201 @@ fn points_show_guides_to_the_points_they_line_up_with() { assert_eq!(guides, [guide]); } +/// Targets reaching 5 points, with nodes in `rects`. +fn nodes(rects: &[Rect]) -> Targets { + let mut targets = Targets::new(5.0); + for &rect in rects { + targets.add_node(rect); + } + targets +} + +fn block(rect: Rect) -> Vec { + Feature::block(&[rect]) +} + +/// A row of nodes 0 to 100 and 300 to 400 along x, 50 high. +fn two_apart() -> Targets { + nodes(&[rect(0.0, 0.0, 100.0, 50.0), rect(300.0, 0.0, 100.0, 50.0)]) +} + +#[test] +fn blocks_snap_halfway_between_the_nodes_beside_them() { + let targets = two_apart(); + // 3 left of halfway. + assert_eq!( + targets.snap(&block(rect(147.0, 10.0, 100.0, 30.0))), + [Some(3.0), None] + ); + let gaps = EqualGaps { + axis: Axis::X, + gaps: vec![[100.0, 150.0], [250.0, 300.0]], + band: [10.0, 40.0], + start: 0.0, + }; + let snapped = block(rect(150.0, 10.0, 100.0, 30.0)); + assert_eq!(targets.equal_gaps(&snapped), [gaps]); +} + +#[test] +fn blocks_snap_as_far_past_a_node_as_it_is_past_the_next() { + // 2 further from the second node than it is from the first. + let targets = nodes(&[rect(0.0, 0.0, 100.0, 50.0), rect(150.0, 0.0, 100.0, 50.0)]); + assert_eq!( + targets.snap(&block(rect(302.0, 0.0, 60.0, 50.0))), + [Some(-2.0), None] + ); + let gaps = EqualGaps { + axis: Axis::X, + gaps: vec![[100.0, 150.0], [250.0, 300.0]], + band: [0.0, 50.0], + start: 0.0, + }; + let snapped = block(rect(300.0, 0.0, 60.0, 50.0)); + assert_eq!(targets.equal_gaps(&snapped), [gaps]); + // And the other way, 2 nearer. + let targets = nodes(&[rect(300.0, 0.0, 100.0, 50.0), rect(450.0, 0.0, 100.0, 50.0)]); + assert_eq!( + targets.snap(&block(rect(192.0, 0.0, 60.0, 50.0))), + [Some(-2.0), None] + ); +} + +#[test] +fn columns_space_too() { + let targets = nodes(&[rect(0.0, 0.0, 50.0, 100.0), rect(0.0, 300.0, 50.0, 100.0)]); + assert_eq!( + targets.snap(&block(rect(10.0, 147.0, 30.0, 100.0))), + [None, Some(3.0)] + ); +} + +#[test] +fn a_block_of_several_boxes_spaces_as_one() { + let boxes = [rect(147.0, 10.0, 40.0, 30.0), rect(207.0, 20.0, 40.0, 30.0)]; + assert_eq!(two_apart().snap(&Feature::block(&boxes)), [Some(3.0), None]); +} + +#[test] +fn only_nodes_overlapping_the_block_across_are_beside_it() { + // The second node is below it. + let targets = nodes(&[rect(0.0, 0.0, 100.0, 50.0), rect(300.0, 100.0, 100.0, 50.0)]); + assert_eq!( + targets.snap(&block(rect(147.0, 10.0, 100.0, 30.0))), + [None, None] + ); + // Beside a taller block, but not beside each other. + let targets = nodes(&[rect(0.0, 0.0, 100.0, 50.0), rect(300.0, 150.0, 100.0, 50.0)]); + assert_eq!( + targets.snap(&block(rect(147.0, 0.0, 100.0, 200.0))), + [None, None] + ); + // Its top only touches their bottoms. + assert_eq!( + two_apart().snap(&block(rect(147.0, 50.0, 100.0, 30.0))), + [None, None] + ); +} + +#[test] +fn only_the_nearest_nodes_count() { + let mut targets = two_apart(); + // Between the block and the node right of it. + targets.add_node(rect(260.0, 0.0, 20.0, 50.0)); + assert_eq!( + targets.snap(&block(rect(147.0, 10.0, 100.0, 30.0))), + [None, None] + ); +} + +#[test] +fn touching_nodes_make_no_gaps() { + let targets = nodes(&[rect(0.0, 0.0, 100.0, 50.0), rect(100.0, 0.0, 100.0, 50.0)]); + let touching = block(rect(200.0, 0.0, 50.0, 50.0)); + assert_eq!( + targets.snap(&block(rect(202.0, 0.0, 50.0, 50.0))), + [None, None] + ); + assert_eq!(targets.equal_gaps(&touching), []); +} + +#[test] +fn the_nearest_of_gaps_and_lines_wins() { + let moved = rect(147.0, 32.0, 100.0, 6.0); + let features = [lines_of(moved), block(moved)].concat(); + // Below, its left side 2 right of the block's, nearer than halfway. + let mut targets = two_apart(); + targets.add_node(rect(149.0, 200.0, 30.0, 30.0)); + assert_eq!(targets.snap(&features), [Some(2.0), None]); + // 4 right, further. + let mut targets = two_apart(); + targets.add_node(rect(151.0, 200.0, 30.0, 30.0)); + assert_eq!(targets.snap(&features), [Some(3.0), None]); +} + +#[test] +fn a_run_takes_in_every_equal_gap_along_the_row() { + let row = [0.0, 150.0, 300.0].map(|x| rect(x, 0.0, 100.0, 50.0)); + let mut targets = nodes(&row); + // Nearer the first node than the gaps. + targets.add_node(rect(-70.0, 0.0, 60.0, 50.0)); + let gaps = EqualGaps { + axis: Axis::X, + gaps: vec![[100.0, 150.0], [250.0, 300.0], [400.0, 450.0]], + band: [0.0, 50.0], + start: 0.0, + }; + let snapped = block(rect(450.0, 0.0, 60.0, 50.0)); + assert_eq!(targets.equal_gaps(&snapped), [gaps]); +} + +#[test] +fn a_run_goes_both_ways_from_halfway() { + let row = [0.0, 150.0, 400.0, 550.0].map(|x| rect(x, 0.0, 100.0, 50.0)); + let gaps = EqualGaps { + axis: Axis::X, + gaps: vec![ + [100.0, 150.0], + [250.0, 300.0], + [350.0, 400.0], + [500.0, 550.0], + ], + band: [0.0, 50.0], + start: 0.0, + }; + let snapped = block(rect(300.0, 0.0, 50.0, 50.0)); + assert_eq!(nodes(&row).equal_gaps(&snapped), [gaps]); +} + +#[test] +fn unequal_gaps_either_side_make_a_run_each() { + let row = [(0.0, 100.0), (150.0, 100.0), (380.0, 100.0), (500.0, 100.0)]; + let targets = nodes(&row.map(|(x, width)| rect(x, 0.0, width, 50.0))); + let run = |gaps: Vec<[f64; 2]>| EqualGaps { + axis: Axis::X, + gaps, + band: [0.0, 50.0], + start: 0.0, + }; + let snapped = block(rect(300.0, 0.0, 60.0, 50.0)); + assert_eq!( + targets.equal_gaps(&snapped), + [ + run(vec![[100.0, 150.0], [250.0, 300.0]]), + run(vec![[360.0, 380.0], [480.0, 500.0]]), + ] + ); +} + +#[test] +fn nodes_in_a_run_all_overlap_one_band() { + // The first node is beside the block, but not beside the second node. + let targets = nodes(&[rect(0.0, 60.0, 100.0, 40.0), rect(150.0, 0.0, 100.0, 40.0)]); + let tall = |x: f64| block(rect(x, 0.0, 60.0, 100.0)); + assert_eq!(targets.snap(&tall(302.0)), [None, None]); + assert_eq!(targets.equal_gaps(&tall(300.0)), []); +} + fn point(x: f64, y: f64) -> Point { Point { x, y } }