2bc41aeb8602
targets.rs
use super::snap::{Leave, meeting, seg_direction, touch_params};
use super::{
Affine, Arc, BezPath, Document, FontDb, GlyphSnap, GuideStyle, Handle, HashSet, Line, Node, NodeId, NodeKind, OrientedBox, Overlay, ParamCurve,
ParamCurveNearest, PathSeg, Point, Rect, Ruler, Selection, Shape, SubPath, ToolContext, Vec2, layout_text,
};
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Kind {
Anchor,
Center,
Edge,
Artboard,
Bleed,
Guide,
Glyph,
}
impl Kind {
fn label(self) -> &'static str {
match self {
Kind::Anchor => "anchor",
Kind::Center => "center",
Kind::Edge => "path",
Kind::Artboard => "artboard",
Kind::Bleed => "bleed",
Kind::Guide => "guide",
Kind::Glyph => "glyph",
}
}
}
/// Snap targets gathered from the document (excluding the objects being edited).
#[derive(Default)]
pub struct Targets {
pub(super) points: Vec<(Point, Kind)>,
pub(super) xs: Vec<(f64, Point, Kind)>,
pub(super) ys: Vec<(f64, Point, Kind)>,
/// Path segments and their control bounds, which a point lands on ("path"): gathered only for
/// dragged anchors ([`Self::for_anchor_drag`]) and selections moved by an anchor
/// ([`Self::for_move_by_anchor`]).
pub(super) segments: Vec<(Rect, PathSeg)>,
/// Ruler guides, which pull a point into line where they run (Snap to Point).
pub(super) rulers: Vec<Ruler>,
/// The bounds of the objects a moved selection spaces itself evenly with (Spacing Guides):
/// gathered only for moves ([`Self::for_move`]).
pub(super) boxes: Vec<Rect>,
/// Line Extension: the lines a single dragged anchor keeps to, along the straight segments
/// it ends, as the end that stays put and the unit direction towards the dragged one
/// ([`Self::for_anchor_drag`]).
pub(super) extensions: Vec<(Point, Vec2)>,
/// Snap to Glyph's guides that run at an angle (in rotated type, or along a glyph's slanted
/// segments), as a point on each and its unit direction: a drawn point lands on the nearest
/// ([`Self::for_drawing`]).
pub(super) angled: Vec<(Point, Vec2)>,
/// Snap to Tangent and Snap to Perpendicular: a drawn line from an anchor lands where it
/// grazes a curve, or meets a segment square ([`Self::touching`]).
pub(super) tangent: bool,
pub(super) perpendicular: bool,
/// How the guides these targets produce look.
pub(super) style: GuideStyle,
/// Smart Guides āŗ Snap to Last Location: a move goes back to where it began when it comes near
/// ([`Self::snap_back`]). Set only for moving the selection itself ([`Self::for_move`]).
pub(super) last_location: bool,
}
/// How many anchors, and how many segments, the targets gather at most.
pub(super) const BUDGET: usize = 20_000;
/// What [`Targets::collect_inner`] gathers from each path besides its anchors and bounds.
#[derive(Clone, Copy, PartialEq)]
enum Gather {
/// Nothing more: a moved or resized selection lines up with bounds.
Bounds,
/// Its segments, which a dragged anchor lands on.
Segments,
/// Its segments, and its anchors as lines too: a drawn point lines up with them.
Drawing,
}
/// The entries of `sorted` (ascending by `key`) whose key is within `tol` of `v`, found by
/// bisection.
fn within<T>(sorted: &[T], key: impl Fn(&T) -> f64, v: f64, tol: f64) -> &[T] {
let lo = sorted.partition_point(|e| key(e) < v - tol);
let hi = sorted.partition_point(|e| key(e) <= v + tol);
sorted.get(lo..hi).unwrap_or_default()
}
/// Visit `nodes` and everything inside them, but the nodes in `skip`, the hidden nodes and
/// everything inside those: one pass, however many are skipped. A Shaper Group's original
/// shapes, its first child, are not shown and are skipped too.
pub(super) fn walk_but<'a>(nodes: &'a [Arc<Node>], skip: &HashSet<NodeId>, f: &mut impl FnMut(&'a Node)) {
for n in nodes.iter().filter(|n| n.visible && !skip.contains(&n.id)) {
f(n);
if let Some(ch) = n.children() {
walk_but(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), skip, f);
}
}
}
/// The lines of `lines` (sorted by where they run) within `tol` of `v`.
pub(super) fn lines_near(lines: &[(f64, Point, Kind)], v: f64, tol: f64) -> &[(f64, Point, Kind)] {
within(lines, |l| l.0, v, tol)
}
/// `r`'s extent along the x axis (`x`) or the y axis.
pub(super) fn span(r: &Rect, x: bool) -> (f64, f64) {
if x { (r.x0, r.x1) } else { (r.y0, r.y1) }
}
/// Is `v` square to the direction `d` (both nonzero)?
fn square_to(v: Vec2, d: Vec2) -> bool {
let scale = v.hypot() * d.hypot();
scale > 1e-18 && v.dot(d).abs() <= 1e-9 * scale
}
/// Do the directions `a` and `b` (both nonzero) run the same way?
fn parallel(a: Vec2, b: Vec2) -> bool {
let scale = a.hypot() * b.hypot();
scale > 1e-18 && a.dot(b) > 0.0 && a.cross(b).abs() <= 1e-6 * scale
}
/// `seg` as a line from its start to its end when it runs straight: a line, or a curve whose
/// control points lie on that line and that stays between its ends (a straight path with its
/// handles drawn out along it).
fn straight(seg: PathSeg) -> Option<Line> {
use vectorcraft_geom::kurbo::ParamCurveExtrema;
let (l, ctrl) = match seg {
PathSeg::Line(l) => return Some(l),
PathSeg::Quad(q) => (Line::new(q.p0, q.p2), [q.p1, q.p1]),
PathSeg::Cubic(c) => (Line::new(c.p0, c.p3), [c.p1, c.p2]),
};
let d = l.p1 - l.p0;
let len2 = d.hypot2();
if !len2.is_finite() || len2 <= 1e-18 || !ctrl.into_iter().all(|p| d.cross(p - l.p0).abs() <= 1e-9 * len2) {
return None;
}
// The curve's own bounds, not its control points', must stay within the ends' box.
let (b, ends) = (ParamCurveExtrema::bounding_box(&seg), Rect::from_points(l.p0, l.p1));
let eps = 1e-9 * len2.sqrt();
(b.x0 >= ends.x0 - eps && b.x1 <= ends.x1 + eps && b.y0 >= ends.y0 - eps && b.y1 <= ends.y1 + eps).then_some(l)
}
/// Does the curve `seg` run around `center` the whole way, as an arc of a circle about it drawn
/// with curves does: nearly square to the center all along, and its distance from the center
/// varying by no more than 0.03%? A circle drawn with four curves ([`vectorcraft_geom::shapes::ellipse`])
/// strays outward from its radius by up to 0.0273%, so an ellipse whose axes differ by less than
/// that cannot be told from one. A circle around the center then lies along the curve.
fn runs_round(seg: &PathSeg, center: Point) -> bool {
const SAMPLES: [f64; 9] = [0.0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0];
if matches!(seg, PathSeg::Line(_)) {
return false;
}
let (mut lo, mut hi) = (f64::INFINITY, 0.0_f64);
for t in SAMPLES {
let (v, d) = (seg.eval(t) - center, seg_direction(seg, t));
if v.dot(d).abs() > 2e-3 * v.hypot() * d.hypot() {
return false;
}
(lo, hi) = (lo.min(v.hypot()), hi.max(v.hypot()));
}
hi - lo <= 3e-4 * hi
}
/// Whether a segment of `segs` other than the `i`th carries on past the end `at` of the `i`th
/// (its start when `at_start`) in the same direction: it has an end at `at` and runs away from
/// it the way the `i`th runs out through it, so the two join smoothly there rather than overlap.
fn continues_smoothly(segs: &[&PathSeg], i: usize, at: Point, at_start: bool) -> bool {
let Some(seg) = segs.get(i) else { return false };
let d = end_direction(seg, at_start);
let out = if at_start { -d } else { d };
let close = 1e-9 * (1.0 + at.x.abs().max(at.y.abs()));
segs.iter().enumerate().filter(|(j, _)| *j != i).any(|(_, s)| {
[(true, s.start()), (false, s.end())].into_iter().any(|(start, end)| {
let d = end_direction(s, start);
end.distance(at) <= close && parallel(if start { d } else { -d }, out)
})
})
}
/// The direction `seg` runs at its start (`at_start`) or its end. Where a curve's handle lies on
/// its anchor the derivative there is zero, so the direction is taken toward the next control
/// point that differs from the anchor, the direction the curve leaves the anchor in.
fn end_direction(seg: &PathSeg, at_start: bool) -> Vec2 {
let mut points: Vec<Point> = match seg {
PathSeg::Line(l) => vec![l.p0, l.p1],
PathSeg::Quad(q) => vec![q.p0, q.p1, q.p2],
PathSeg::Cubic(c) => vec![c.p0, c.p1, c.p2, c.p3],
};
if !at_start {
points.reverse();
}
let Some((&anchor, rest)) = points.split_first() else { return Vec2::ZERO };
let away = rest.iter().map(|q| *q - anchor).find(|v| v.hypot2() > 0.0).unwrap_or(Vec2::ZERO);
if at_start { away } else { -away }
}
/// The points inside `seg` where the line from `center` meets it square, where a circle round
/// `center` touches it, with the segment's direction there. A straight segment has at most one, its
/// foot of the perpendicular. On a curve, besides the sign changes [`touch_params`] finds, a sample
/// where the line is square exactly counts too: a center straight out from a symmetric curve's
/// middle meets it square at t = 0.5.
fn radial_touches(seg: &PathSeg, center: Point) -> Vec<(Point, Vec2)> {
/// The samples checked for an exact square meeting, as [`touch_params`] samples the curve.
const STEPS: u32 = 24;
if let PathSeg::Line(l) = seg {
let d = l.p1 - l.p0;
let t = (center - l.p0).dot(d) / d.hypot2();
return if t.is_finite() && t > 0.0 && t < 1.0 { vec![(l.p0 + d * t, d)] } else { vec![] };
}
let sampled = (1..STEPS).map(|i| f64::from(i) / f64::from(STEPS)).filter(|&t| square_to(seg.eval(t) - center, seg_direction(seg, t)));
sampled.chain(touch_params(seg, center, true)).map(|t| (seg.eval(t), seg_direction(seg, t))).collect()
}
/// Along axis `x`, does dragging `handle` move the box's minimum edge (true) or maximum (false)?
fn resize_moves_min_edge(handle: Handle, x: bool) -> Option<bool> {
let (ax, ay) = handle.axes();
if x && !ax || !x && !ay {
return None;
}
if x {
Some(matches!(handle, Handle::Left | Handle::TopLeft | Handle::BottomLeft))
} else {
Some(matches!(handle, Handle::Top | Handle::TopLeft | Handle::TopRight))
}
}
/// The objects a moved selection (`moving`) spaces itself evenly with, by their bounds: each
/// visible object on a layer as a whole (a group too), and inside a group holding some of the
/// moving objects its other objects, but a Shaper Group's original shapes. At most [`BUDGET`].
pub(super) fn object_boxes(doc: &Document, moving: &[NodeId]) -> Vec<Rect> {
fn push(nodes: &[Arc<Node>], moving: &HashSet<NodeId>, holders: &HashSet<NodeId>, out: &mut Vec<Rect>) {
for n in nodes.iter().filter(|n| n.visible && !moving.contains(&n.id)) {
if out.len() >= BUDGET {
return;
}
match n.children() {
Some(ch) if n.is_layer() || holders.contains(&n.id) => {
push(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), moving, holders, out)
}
_ => out.extend(n.geometric_bounds()),
}
}
}
let holders: HashSet<NodeId> = moving.iter().filter_map(|id| doc.ancestry(*id)).flatten().collect();
let mut out = vec![];
push(&doc.layers, &moving.iter().copied().collect(), &holders, &mut out);
out
}
/// The corners of glyph `g`'s bounding box in text space, clockwise from its top left as drawn:
/// the box of its outline in its own frame (font units), through `g.xf`, so it turns, slants and
/// scales with the glyph. `bb` is the outline's box in text space, used as it is for a glyph bent
/// along a path or with a frame that can't be undone.
fn glyph_box(g: &vectorcraft_text::PositionedGlyph, bb: &Rect) -> [Point; 4] {
let corners = |r: Rect| [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
let det = g.xf.determinant();
if g.bend.is_some() || !(det.is_finite() && det.abs() > 1e-12) {
return corners(*bb);
}
let local = (g.xf.inverse() * g.outline.clone()).bounding_box();
if !(local.is_finite() && local.width() > 0.0 && local.height() > 0.0) {
return corners(*bb);
}
corners(local).map(|p| g.xf * p)
}
impl Targets {
pub fn collect(doc: &Document, exclude: &[NodeId], visible: Option<Rect>) -> Self {
Self::collect_inner(doc, exclude, None, visible, Gather::Bounds)
}
/// Targets for moving the selection of `cx`: [`Self::collect`]'s but `exclude` (the selection,
/// or nothing for a copy, which leaves it behind), styled as `cx` asks, and with Smart Guides āŗ
/// Spacing Guides the objects it spaces itself evenly with ([`Self::snap_rect`]). With Smart
/// Guides āŗ Snap to Last Location, a move (not a copy, which has nothing in `exclude`) goes back
/// to where it began when it comes near ([`Self::snap_back`]), unless Snap to Pixel snaps moves.
pub fn for_move(cx: &ToolContext, exclude: &[NodeId]) -> Self {
Self::moving(cx, exclude, Gather::Bounds)
}
/// [`Self::for_move`]'s targets for a selection moved by one of its anchors (#7411) or by a
/// point of a path's stroke or outline (#8568): the path segments of the art but `exclude` too,
/// which that point lands on ([`Self::snap_onto_path`]), as a dragged anchor does with Direct
/// Selection.
pub fn for_move_by_anchor(cx: &ToolContext, exclude: &[NodeId]) -> Self {
Self::moving(cx, exclude, Gather::Segments)
}
fn moving(cx: &ToolContext, exclude: &[NodeId], gather: Gather) -> Self {
let mut t = Self::collect_inner(cx.doc, exclude, None, None, gather).styled(cx);
if cx.spacing_guides {
t.boxes = object_boxes(cx.doc, &cx.selection.objects);
}
t.last_location = cx.snap_to_last_location && !cx.snaps_to_pixel(crate::PixelOp::Moving) && !exclude.is_empty();
t
}
/// Smart Guides āŗ Snap to Last Location: a move by `d` that is no farther than `tol` from
/// where it began goes back there. Returns the guides for it, a "last location" label at the
/// center of `from` (the moved bounds when the move began), or None when the move stays where
/// it is: the option is off, the targets are for a copy, or `d` is longer than `tol`.
pub fn snap_back(&self, from: Option<Rect>, d: Vec2, tol: f64) -> Option<Vec<Overlay>> {
(self.last_location && d.hypot() <= tol).then(|| from.and_then(|r| self.label(r.center(), "last location")).into_iter().collect())
}
/// Targets that hold nothing but Smart Guides āŗ Snap to Last Location ([`Self::snap_back`]),
/// styled as `cx` asks: for a move of the selection whose other snaps come from other targets,
/// such as paths selected whole that Direct Selection moves held by an anchor. Snap to Pixel
/// snapping moves turns it off, as it does every Smart Guides snap.
pub fn last_location(cx: &ToolContext) -> Self {
Self { last_location: cx.snap_to_last_location && !cx.snaps_to_pixel(crate::PixelOp::Moving), ..Self::default() }.styled(cx)
}
/// Targets for scaling the selection: the other art, styled as `cx` asks, and with Smart Guides āŗ
/// Spacing Guides the neighbours whose gaps the moving edge should match ([`Self::snap_scale`]).
pub fn for_scale(cx: &ToolContext) -> Self {
Self { last_location: false, ..Self::for_move(cx, &cx.selection.objects) }
}
/// Targets for a drawn point: the art in `visible` (all of it for None) but `exclude`, its
/// anchors, centres, edges and path segments, its anchors in line too. The anchors and
/// segments of `exclude` (the path being drawn, whose bounds grow with it) stay targets. With
/// `glyphs` (Snap to Glyph on), live text gives the guides those options ask for.
pub fn for_drawing(doc: &Document, exclude: &[NodeId], visible: Option<Rect>, glyphs: Option<GlyphSnap>) -> Self {
let mut t = Self::collect_inner(doc, exclude, None, visible, Gather::Drawing);
t.push_paths(doc, exclude, true);
if let Some(o) = glyphs {
t.push_glyphs(doc, exclude, visible, o);
}
t.index()
}
/// Targets for the ends of a measurement: [`Self::collect`]'s, and with `glyphs` (Snap to Glyph
/// on) the guides those options ask for from the live text in `visible` (all of it for None),
/// without the outlines' anchor points, which Anchor Point gives the Pen and moved objects.
pub fn for_measure(doc: &Document, visible: Option<Rect>, glyphs: Option<GlyphSnap>) -> Self {
let mut t = Self::collect(doc, &[], None);
if let Some(o) = glyphs {
t.push_glyphs(doc, &[], visible, GlyphSnap { anchors: false, ..o });
}
t.index()
}
/// Targets for a dragged direction handle of path `id`: the other art, and the anchors of `id`
/// (its bounds and the segments through the handle move with it, so they would chase it).
pub fn for_handle(doc: &Document, id: NodeId) -> Self {
let mut t = Self::collect_inner(doc, &[id], None, None, Gather::Bounds);
t.push_paths(doc, &[id], false);
t.index()
}
/// The anchors of the paths `ids` as targets, on them and in line, and their segments too
/// when `segments`: at most [`BUDGET`] of each.
fn push_paths(&mut self, doc: &Document, ids: &[NodeId], segments: bool) {
let (mut anchors, mut segment_budget) = (BUDGET, if segments { BUDGET } else { 0 });
for path in ids.iter().filter_map(|id| doc.node(*id)?.path_data()) {
for sp in &path.subpaths {
for a in sp.anchors.iter().take(anchors) {
self.push_anchor(a.p);
anchors -= 1;
}
self.push_segments(sp, |_| false, &mut segment_budget);
}
}
}
/// Sort the targets so that [`within`] finds those near a point by bisection: the anchors
/// and centres by x, the lines by where they run. Every constructor ends with it (the sort
/// is stable: of targets alike, the first gathered still wins).
fn index(mut self) -> Self {
self.points.sort_by(|a, b| a.0.x.total_cmp(&b.0.x));
self.xs.sort_by(|a, b| a.0.total_cmp(&b.0));
self.ys.sort_by(|a, b| a.0.total_cmp(&b.0));
self
}
/// Anchor `a` as a target: a point lands on it and lines up with it.
fn push_anchor(&mut self, a: Point) {
self.points.push((a, Kind::Anchor));
self.xs.push((a.x, a, Kind::Anchor));
self.ys.push((a.y, a, Kind::Anchor));
}
/// A glyph guide through `at` along `dir` (on the page): a line the art lines up with when it
/// runs across or down the page, else (with `angular`, Angular Guides) an angled line a point
/// lands on.
fn push_glyph_line(&mut self, at: Point, dir: Vec2, angular: bool) {
let len = dir.hypot();
if !(len.is_finite() && len > 1e-12 && at.is_finite()) {
return;
}
let d = dir / len;
if d.y.abs() <= 1e-9 {
self.ys.push((at.y, at, Kind::Glyph));
} else if d.x.abs() <= 1e-9 {
self.xs.push((at.x, at, Kind::Glyph));
} else if angular {
self.angled.push((at, d));
}
}
/// Live text as View āŗ Snap to Glyph shows it: the glyph bounds of every text object, and for
/// a single line of type also its baseline and x-height, the proximity guides at the edges of
/// each character's advance width, and its glyphs' anchor points. In rotated type these
/// guides run at its angle (angular guides), and type of one glyph also has angular guides
/// along the glyph's slanted straight segments. Each kind of guide is there only while its
/// option `o` is on.
fn push_glyphs(&mut self, doc: &Document, exclude: &[NodeId], visible: Option<Rect>, o: GlyphSnap) {
let skip: HashSet<NodeId> = exclude.iter().copied().collect();
let db = FontDb::global();
let kind = Kind::Glyph;
let mut budget = BUDGET / 4;
let (mut anchors, mut angular) = (BUDGET, BUDGET / 4);
walk_but(&doc.layers, &skip, &mut |n| {
if budget == 0 || !n.visible {
return;
}
let NodeKind::Text(t) = &n.kind else { return };
let lay = layout_text(db, t);
let ink = t.xf.transform_rect_bbox(lay.bounds);
if !ink.is_finite() || ink.width() <= 0.0 || ink.height() <= 0.0 {
return;
}
if let Some(v) = visible
&& ink.intersect(v).area() <= 0.0
&& !v.contains(ink.center())
{
return;
}
// A paragraph shows glyph bounds only.
let single = lay.lines.len() == 1;
// Angular guides along a glyph's slanted segments: type of one glyph only.
let one_glyph = lay.glyphs.iter().filter(|g| !g.outline.elements().is_empty()).count() == 1;
// Text space ā the page, and a direction in text space ā one on the page.
let to_doc = |p: Point| t.xf * p;
let along = |m: Affine, v: Vec2| (m * v.to_point()) - (m * Point::ZERO);
if single && o.baseline {
let line_doc = t.xf * lay.line_xf;
for line in &lay.lines {
self.push_glyph_line(line_doc * Point::new(line.x0, line.baseline), along(line_doc, Vec2::new(1.0, 0.0)), o.angular);
}
}
// The last x-height pushed, to push each run of glyphs alike once.
let mut last_x_height: Option<(Point, Vec2)> = None;
for g in &lay.glyphs {
if budget == 0 {
break;
}
// Glyphs that draw nothing (spaces) give no guides.
let bb = g.outline.bounding_box();
if !(bb.width() > 0.0 && bb.height() > 0.0) {
continue;
}
budget -= 1;
// Horizontal type and type on a path: the baseline runs from where the pen stood
// along the glyph's angle (not the glyph's own drawing, which Character Rotation
// turns), up being to its left.
if single
&& !lay.vertical
&& let Some(face) = db.face_by_id(g.font_id)
{
let ahead = Vec2::new(g.angle.cos(), g.angle.sin());
let up = Vec2::new(ahead.y, -ahead.x);
let dir = along(t.xf, ahead);
// The x-height of the glyph as placed without its Character Rotation (raised or
// lowered by its baseline shift), measured across the baseline.
let top = g.xf * g.unturned * Point::new(0.0, -face.x_height());
let at = to_doc(g.origin + up * (top - g.origin).dot(up));
let same = last_x_height.is_some_and(|(a, d)| {
let (l, k) = (d.hypot(), dir.hypot());
l > 1e-12 && k > 1e-12 && (d / l - dir / k).hypot() <= 1e-9 && ((at - a).cross(d / l)).abs() <= 1e-6
});
if o.x_height && face.x_height() > 0.0 && !same {
self.push_glyph_line(at, dir, o.angular);
last_x_height = Some((at, dir));
}
// Proximity guides: across the baseline at both edges of the width the layout
// gives the character (its advance with tracking and kerning).
if o.proximity {
for e in [g.origin, g.origin + ahead * g.advance] {
self.push_glyph_line(to_doc(e), along(t.xf, up), o.angular);
}
}
}
if single {
for seg in g.outline.segments() {
if o.anchors && anchors > 0 {
self.points.push((to_doc(seg.start()), Kind::Anchor));
anchors -= 1;
}
if o.angular
&& one_glyph
&& angular > 0
&& let PathSeg::Line(l) = seg
{
let (p, q) = (to_doc(l.p0), to_doc(l.p1));
let d = q - p;
let len = d.hypot();
if len > 1e-6 && d.x.abs() > 1e-9 * len && d.y.abs() > 1e-9 * len {
self.push_glyph_line(p, d, true);
angular -= 1;
}
}
}
}
if o.bounds {
// The glyph's box in its own frame (font units), placed as the glyph is: its
// corners are points to land on, even where the outline curves (the right of
// `B`), and its edges guides, which turn with rotated or slanted type.
let corners = glyph_box(g, &bb).map(to_doc);
for (i, c) in corners.iter().enumerate() {
self.points.push((*c, kind));
let next = corners.get((i + 1) % 4).copied().unwrap_or(*c);
self.push_glyph_line(*c, next - *c, o.angular);
}
}
}
});
}
/// The same targets drawing their guides as the Smart Guides preferences in `cx` ask
/// ([`GuideStyle::of`]).
pub fn styled(mut self, cx: &ToolContext) -> Self {
self.style = GuideStyle::of(cx);
self
}
/// An alignment line from `a` to `b`, unless Alignment Guides are off.
fn line(&self, a: Point, b: Point) -> Option<Overlay> {
self.style.lines.then_some(Overlay::Line { a, b, color: self.style.color, dashed: false })
}
/// A label `text` at `p`, unless Anchor/Path Labels are off.
pub(super) fn label(&self, p: Point, text: &str) -> Option<Overlay> {
self.style.labels.then(|| Overlay::Label { p, text: text.into(), color: self.style.color })
}
/// Targets for dragging artboard `index`: everything except that artboard and `exclude` (the
/// art that moves along with it).
pub fn for_artboard(doc: &Document, index: usize, exclude: &[NodeId]) -> Self {
Self::collect_inner(doc, exclude, Some(index), None, Gather::Bounds)
}
/// Targets for dragging the direct-selected anchors of `sel` (and its objects selected as a
/// whole): the other art, its path segments too, and the anchors and segments that stay put on
/// the paths being reshaped (their bounds move along, so they are no targets). A single anchor
/// also keeps to the extensions of the straight segments it ends (#2120).
pub fn for_anchor_drag(doc: &Document, sel: &Selection) -> Self {
let mut t = Self::collect_inner(doc, &sel.objects, None, None, Gather::Segments);
let (mut anchors, mut segments) = (BUDGET, BUDGET);
// With several anchors moving, the one under the pointer is not known here, and the
// others' extensions don't run through it.
let single = sel.objects.len() <= 1 && sel.anchors.values().map(|s| s.len()).sum::<usize>() == 1;
// A path inside another selected object, such as a path in a selected group, moves whole
// with that object, so none of its anchors or segments stay put.
let selected: HashSet<NodeId> = sel.objects.iter().copied().collect();
let inside_selected = |id: NodeId| doc.ancestry(id).is_some_and(|a| a.iter().rev().skip(1).any(|p| selected.contains(p)));
for (id, set) in sel.anchors.iter().filter(|(id, _)| !inside_selected(**id)) {
let Some(path) = doc.node(*id).and_then(|n| n.path_data()) else { continue };
for (si, sp) in path.subpaths.iter().enumerate() {
let moving = |ai: usize| set.contains(&(si, ai));
for a in sp.anchors.iter().enumerate().filter(|(ai, _)| !moving(*ai)).map(|(_, a)| a.p).take(anchors) {
t.push_anchor(a);
anchors -= 1;
}
t.push_segments(sp, moving, &mut segments);
if single {
t.push_extensions(sp, moving);
}
}
}
t.index()
}
/// The extensions of the straight segments of `sp` with one end among the anchors `moving`
/// accepts and the other staying put. Horizontal and vertical ones are left out: lining up
/// with the other end already keeps the point on them, and says "align".
fn push_extensions(&mut self, sp: &SubPath, moving: impl Fn(usize) -> bool) {
let n = sp.anchors.len();
for seg in (0..sp.segment_count()).filter(|&seg| moving(seg) != moving((seg + 1) % n) && sp.segment_is_line(seg)) {
let c = sp.segment(seg);
let (fixed, dragged) = if moving(seg) { (c.p3, c.p0) } else { (c.p0, c.p3) };
let d = dragged - fixed;
let len = d.hypot();
if len.is_finite() && d.x.abs() > 1e-9 * len && d.y.abs() > 1e-9 * len {
self.extensions.push((fixed, d / len));
}
}
}
/// The segments of `sp` that stay put while the anchors `moving` accepts move, as targets, at
/// most `budget` of them (counted down).
fn push_segments(&mut self, sp: &SubPath, moving: impl Fn(usize) -> bool, budget: &mut usize) {
let n = sp.anchors.len();
for seg in 0..sp.segment_count() {
if *budget == 0 {
return;
}
if moving(seg) || moving((seg + 1) % n) {
continue;
}
let c = sp.segment(seg);
let bounds = Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3);
// A straight one as a line, so the point lands on it exactly.
self.segments.push((bounds, if sp.segment_is_line(seg) { PathSeg::Line(Line::new(c.p0, c.p3)) } else { PathSeg::Cubic(c) }));
*budget -= 1;
}
}
fn collect_inner(doc: &Document, exclude: &[NodeId], skip_artboard: Option<usize>, visible: Option<Rect>, gather: Gather) -> Self {
let mut t = Targets::default();
let add_rect = |t: &mut Targets, r: Rect, kind: Kind| {
let c = r.center();
for p in [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)] {
t.xs.push((p.x, p, kind));
t.ys.push((p.y, p, kind));
}
// A bleed shares its artboard's centre.
if kind != Kind::Bleed {
t.points.push((c, Kind::Center));
t.xs.push((c.x, c, Kind::Center));
t.ys.push((c.y, c, Kind::Center));
}
};
for (_, ab) in doc.artboards.iter().enumerate().filter(|(i, _)| Some(*i) != skip_artboard) {
add_rect(&mut t, ab.rect, Kind::Artboard);
if doc.setup.has_bleed() {
add_rect(&mut t, doc.setup.bleed_rect(ab.rect), Kind::Bleed);
}
}
let (mut budget, mut segment_budget) = (BUDGET, BUDGET);
walk_but(&doc.layers, &exclude.iter().copied().collect(), &mut |n| {
if budget == 0 || n.is_container() || !n.visible {
return;
}
let Some(b) = n.geometric_bounds() else { return };
if let Some(v) = visible
&& b.intersect(v).area() <= 0.0
&& !v.contains(b.center())
{
return;
}
if let NodeKind::Path { path, .. } = &n.kind {
for (_, _, a) in path.anchors() {
if gather == Gather::Drawing {
t.push_anchor(a.p);
} else {
t.points.push((a.p, Kind::Anchor));
}
budget = budget.saturating_sub(1);
}
if gather != Gather::Bounds {
for sp in &path.subpaths {
t.push_segments(sp, |_| false, &mut segment_budget);
}
}
}
add_rect(&mut t, b, Kind::Edge);
});
t.index()
}
/// Only these targets' anchors pull (View ā Snap to Point).
pub(crate) fn anchors_only(mut self) -> Self {
self.points.retain(|(_, k)| *k == Kind::Anchor);
self.xs.clear();
self.ys.clear();
self.segments.clear();
self.extensions.clear();
self.angled.clear();
self
}
/// Only these targets' anchors and path segments pull, and where segments cross: no centers,
/// bounds, lines up, extensions or glyph guides.
pub(super) fn anchors_and_paths(mut self) -> Self {
self.points.retain(|(_, k)| *k == Kind::Anchor);
self.xs.clear();
self.ys.clear();
self.rulers.clear();
self.boxes.clear();
self.extensions.clear();
self.angled.clear();
self
}
/// View ā Snap to Point: only these targets' anchors pull, and the ruler guides (shown and
/// unlocked, as the selection tools pick them) pull the pointer into line where they run. It
/// snaps without Smart Guides, so it draws none of their labels and lines.
pub(super) fn for_snap_to_point(mut self, cx: &ToolContext) -> Self {
self.style = GuideStyle { lines: false, labels: false, ..GuideStyle::of(cx) };
self.anchors_only().with_rulers(cx)
}
/// These targets and the ruler guides, when they are shown (and so unlocked to the selection
/// tools): they pull a point into line where they run.
pub(super) fn with_rulers(mut self, cx: &ToolContext) -> Self {
if cx.guides {
self.rulers = cx
.doc
.ruler_guides()
.iter()
.filter(|g| cx.doc.guide_shown(g))
.map(|g| Ruler { vertical: g.vertical, pos: g.pos, span: cx.doc.guide_span(g) })
.collect();
}
self
}
/// The ruler guides alone ([`Self::with_rulers`]): what a dragged selection's grabbed point
/// still snaps to with View ā Snap to Point when Smart Guides line the selection up.
pub(crate) fn rulers(cx: &ToolContext) -> Self {
Self::default().styled(cx).with_rulers(cx)
}
/// What a dragged selection's grabbed point snaps to with View ā Snap to Point and Smart
/// Guides off: the anchors of the art but `exclude` and the ruler guides.
pub fn snap_to_point(cx: &ToolContext, exclude: &[NodeId]) -> Option<Self> {
(cx.snap_to_point && !cx.smart_guides).then(|| Self::collect(cx.doc, exclude, None).for_snap_to_point(cx))
}
/// The gridlines (one every `step` from the page's origin, as
/// [`vectorcraft_geom::snap::snap_to_grid`] places them) at and either side of the nearest one
/// to each of `points`, as lines to line up with.
pub(super) fn grid_lines(points: impl IntoIterator<Item = Point>, step: f64) -> Self {
let mut t = Targets::default();
let line = |v: f64, k: i32| vectorcraft_geom::snap::snap_to_grid(v, step, 0.0) + f64::from(k) * step;
for p in points {
for k in -1..=1 {
let (x, y) = (line(p.x, k), line(p.y, k));
t.xs.push((x, Point::new(x, p.y), Kind::Guide));
t.ys.push((y, Point::new(p.x, y), Kind::Guide));
}
}
t.index()
}
/// Anchors and centres of the visible leaves under `roots` (the roots included) whose bounds
/// reach into `near`. Nothing inside a hidden group or layer counts.
pub(super) fn points_near(doc: &Document, roots: &[NodeId], near: Rect) -> Self {
let mut t = Targets::default();
let mut push = |c: &Node| {
if c.is_container() {
return;
}
let Some(b) = c.geometric_bounds() else { return };
if b.x0 > near.x1 || b.x1 < near.x0 || b.y0 > near.y1 || b.y1 < near.y0 {
return;
}
if let NodeKind::Path { path, .. } = &c.kind {
t.points.extend(path.anchors().map(|(_, _, a)| (a.p, Kind::Anchor)));
}
t.points.push((b.center(), Kind::Center));
};
for n in roots.iter().filter_map(|id| doc.node(*id)).filter(|n| n.visible) {
push(n);
if let Some(ch) = n.children() {
walk_but(ch.get(usize::from(n.extras().shaper.is_some())..).unwrap_or_default(), &HashSet::new(), &mut push);
}
}
t.index()
}
/// Snap a single point: onto the nearest anchor or centre, else onto the nearest segment, else
/// into line with targets. Returns the snapped point and guide overlays.
pub fn snap_point(&self, p: Point, tol: f64) -> (Point, Vec<Overlay>) {
self.snap_from(p, None, tol)
}
/// Snap a drawn point `p` as [`Self::snap_point`] does, and when it leaves `from` (the anchor
/// before it, a shape's start): with Shift held it keeps to its angles round it, sliding along
/// that way into line with the nearest target; else, before lining up, it lands on a
/// construction guide through it, where a target's line crosses the guide if one does nearby.
pub fn snap_from(&self, p: Point, from: Option<&Leave>, tol: f64) -> (Point, Vec<Overlay>) {
if let Some(f) = from
&& let Some(q) = f.constrained(p)
{
return match self.slide(f.at, q - f.at, q, tol, true) {
Some((q, target)) => (q, self.lined_up(q, target)),
None => (q, vec![]),
};
}
if let Some((q, k)) = self.nearest_point(p, tol) {
return (q, self.label(q, k.label()).into_iter().collect());
}
if let Some(q) = self.crossing(p, tol) {
return (q, self.label(q, "intersect").into_iter().collect());
}
if let Some(f) = from.filter(|f| f.contact)
&& let Some((q, perpendicular, dir)) = self.touching(f.at, p, tol)
{
return (q, self.touch_guides(f.at, q, perpendicular, dir, tol));
}
if let Some(q) = self.on_segment(p, tol) {
return (q, self.label(q, Kind::Edge.label()).into_iter().collect());
}
// A construction guide through the point it leaves, else a dragged segment's extension:
// it lands on the guide, sliding into line with a target crossing it nearby.
if let Some((at, dir, q)) = from
.and_then(|f| f.construction(p, tol).map(|(dir, q)| (f.at, dir, q)))
.or_else(|| self.extension(p, tol))
.or_else(|| self.on_angled(p, tol))
{
let construction = |q: Point| Overlay::Line { a: at, b: q, color: self.style.color, dashed: false };
return match self.slide(at, dir, q, tol, false) {
Some((q, target)) => (q, std::iter::once(construction(q)).chain(self.lined_up(q, target)).collect()),
None => (q, vec![construction(q)]),
};
}
let mut out = p;
let mut ov = vec![];
// The targets' lines along one axis and the ruler guides running past `p`, the nearest
// within reach of `v`.
let nearest = |lines: &[(f64, Point, Kind)], vertical: bool, v: f64| {
let rulers = self.rulers.iter().filter(|r| r.vertical == vertical).filter_map(|r| r.line_at(p, tol));
lines_near(lines, v, tol)
.iter()
.copied()
.chain(rulers)
.filter(|(t, ..)| (t - v).abs() <= tol)
.min_by(|a, b| (a.0 - v).abs().total_cmp(&(b.0 - v).abs()))
};
let mut aligned = false;
if let Some((x, from, _)) = nearest(&self.xs, true, p.x) {
out.x = x;
aligned = true;
ov.extend(self.line(from, Point::new(x, p.y)));
}
if let Some((y, from, _)) = nearest(&self.ys, false, p.y) {
out.y = y;
aligned = true;
ov.extend(self.line(from, Point::new(p.x, y)));
}
if aligned {
ov.extend(self.label(out, "align"));
}
(out, ov)
}
/// Where a line from `at` through a point near `p` touches a target segment: square to it
/// (`perpendicular`, the foot of the perpendicular from `at`) or just grazing a curve
/// (`tangent`), within `tol` of `p`. The point, whether it is the perpendicular one, and the
/// segment's direction there. Targets gather segments for drawn points and dragged anchors only.
pub(super) fn touching(&self, at: Point, p: Point, tol: f64) -> Option<(Point, bool, Vec2)> {
if !(self.tangent || self.perpendicular) || ![at.x, at.y, p.x, p.y, tol].iter().all(|v| v.is_finite()) {
return None;
}
let mut best: Option<(f64, Point, bool, Vec2)> = None;
// Every segment in reach is tried: their order is the document's, not the distance.
for (_, seg) in self.segments.iter().filter(|(b, _)| b.inflate(tol, tol).contains(p)) {
let curved = !matches!(seg, PathSeg::Line(_));
for (perpendicular, wanted) in [(true, self.perpendicular && !curved), (false, self.tangent && curved)] {
if !wanted {
continue;
}
for t in touch_params(seg, at, perpendicular) {
let (q, d) = (seg.eval(t), seg_direction(seg, t));
let dist = q.distance(p);
if dist <= tol && q.distance(at) > tol && best.is_none_or(|b| dist < b.0) {
best = Some((dist, q, perpendicular, d));
}
}
}
}
best.map(|(_, q, perpendicular, d)| (q, perpendicular, d))
}
/// The guides of a point landed where the line from `at` touches a segment at `q` running
/// along `dir`: the line itself, a square corner mark for the perpendicular, and the label.
fn touch_guides(&self, at: Point, q: Point, perpendicular: bool, dir: Vec2, tol: f64) -> Vec<Overlay> {
let mut out: Vec<Overlay> = self.line(at, q).into_iter().collect();
let (u, v) = (at - q, dir);
if perpendicular && self.style.lines && u.hypot2() > 1e-18 && v.hypot2() > 1e-18 {
let (u, v) = (u / u.hypot(), v / v.hypot());
let s = tol * 1.5;
let mut mark = BezPath::new();
mark.move_to(q + u * s);
mark.line_to(q + u * s + v * s);
mark.line_to(q + v * s);
out.push(Overlay::Path { path: mark, color: self.style.color, width: 1.0, dashed: false });
}
out.extend(self.label(q, if perpendicular { "perpendicular" } else { "tangent" }));
out
}
/// Snap to Tangent for a circle drawn around `center` with radius `r`: the radius nearest `r`,
/// within `tol` of it, at which the circle touches a target segment (where the line from
/// `center` meets the path square, at a point the path runs smoothly through), and the guides
/// showing it. None with an anchor, a center or a crossing within `tol` of the pointer `p`, or
/// at `corner`, where the drawn point snapped to: those win as they do for a drawn point. At
/// most 256 segments are measured, the ones nearest `p` when more cross the ring round
/// `center` at radius `r`.
pub(super) fn tangent_radius(&self, center: Point, p: Point, corner: Point, r: f64, tol: f64) -> Option<(f64, Vec<Overlay>)> {
/// How many segments one pointer move measures at most.
const MAX_SEGMENTS: usize = 256;
let finite = [center.x, center.y, p.x, p.y, corner.x, corner.y, r, tol].iter().all(|v| v.is_finite());
if !self.tangent || !finite || r < 0.0 || tol <= 0.0 {
return None;
}
if self.nearest_point(p, tol).is_some() || self.crossing(p, tol).is_some() {
return None;
}
// The corner snapped onto a point or a crossing: it lies on one, not merely near.
let on = |q: Point| q.distance(corner) <= 1e-9 * (1.0 + corner.x.abs().max(corner.y.abs()));
if self.nearest_point(corner, tol).is_some_and(|(q, _)| on(q)) || self.crossing(corner, tol).is_some_and(on) {
return None;
}
let (lo, hi) = (r - tol, r + tol);
// A segment can touch the circle only if part of its control bounds lies within the ring
// between `lo` and `hi` around the center.
let in_ring = |b: &Rect| {
let near = Point::new(center.x.clamp(b.x0, b.x1), center.y.clamp(b.y0, b.y1)).distance(center);
let far = (center.x - b.x0).abs().max((center.x - b.x1).abs()).hypot((center.y - b.y0).abs().max((center.y - b.y1).abs()));
near <= hi && far >= lo
};
let mut best: Option<(f64, Point, Vec2)> = None;
let mut offer = |q: Point, d: Vec2| {
let rho = q.distance(center);
if rho > tol && (rho - r).abs() <= tol && best.is_none_or(|(b, ..)| (rho - r).abs() < (b - r).abs()) {
best = Some((rho, q, d));
}
};
let mut ring: Vec<&(Rect, PathSeg)> = self.segments.iter().filter(|(b, _)| in_ring(b)).collect();
if ring.len() > MAX_SEGMENTS {
let from_p = |b: &Rect| Point::new(p.x.clamp(b.x0, b.x1), p.y.clamp(b.y0, b.y1)).distance(p);
ring.select_nth_unstable_by(MAX_SEGMENTS, |a, b| from_p(&a.0).total_cmp(&from_p(&b.0)));
ring.truncate(MAX_SEGMENTS);
}
let near: Vec<&PathSeg> = ring.into_iter().map(|(_, s)| s).collect();
for (i, seg) in near.iter().enumerate() {
// A circle around the same center lies along such a curve rather than touching it.
if runs_round(seg, center) {
continue;
}
for (q, d) in radial_touches(seg, center) {
offer(q, d);
}
// At an end square to the center the circle touches the path only where the next
// segment carries on in the same direction: at a corner or an open end it meets it.
// That segment ends on the circle too, so it is in the ring; when more than
// MAX_SEGMENTS segments are in the ring and it is not among those kept, the end is not
// offered.
for (at_start, end) in [(true, seg.start()), (false, seg.end())] {
let d = end_direction(seg, at_start);
if square_to(end - center, d) && continues_smoothly(&near, i, end, at_start) {
offer(end, d);
}
}
}
let (rho, q, d) = best?;
Some((rho, self.touch_guides(center, q, false, d, tol)))
}
/// The segment extension nearest `p`, within `tol` of it (and `p` farther than that from the
/// end it starts at): that end, its direction and where `p` lands on it. Where `p` is nearer
/// the horizontal or the vertical through that end there is none: lining up with it ("align")
/// is what straightens a segment that is nearly level or upright.
fn extension(&self, p: Point, tol: f64) -> Option<(Point, Vec2, Point)> {
self.extensions
.iter()
.filter(|(at, _)| at.distance(p) > tol)
.map(|&(at, d)| (at, d, at + d * (p - at).dot(d)))
.map(|(at, d, q)| (at, d, q, q.distance(p)))
.filter(|(at, .., dist)| *dist <= tol && (p.x - at.x).abs().min((p.y - at.y).abs()) > *dist)
.min_by(|a, b| a.3.total_cmp(&b.3))
.map(|(at, d, q, _)| (at, d, q))
}
/// The angled glyph guide ([`Self::angled`]) nearest `p`, within `tol` of it: a point on it, its
/// direction and where `p` lands on it.
fn on_angled(&self, p: Point, tol: f64) -> Option<(Point, Vec2, Point)> {
self.angled
.iter()
.map(|&(at, d)| (at, d, at + d * (p - at).dot(d)))
.map(|(at, d, q)| (at, d, q, q.distance(p)))
.filter(|(.., dist)| *dist <= tol)
.min_by(|a, b| a.3.total_cmp(&b.3))
.map(|(at, d, q, _)| (at, d, q))
}
/// The anchor or centre nearest `p`, within `tol`.
/// Is a target point (an anchor, a centre) within `tol` of `p`?
pub(crate) fn has_point_near(&self, p: Point, tol: f64) -> bool {
self.nearest_point(p, tol).is_some()
}
pub(super) fn nearest_point(&self, p: Point, tol: f64) -> Option<(Point, Kind)> {
within(&self.points, |q| q.0.x, p.x, tol)
.iter()
.copied()
.filter(|(q, _)| q.distance(p) <= tol)
.min_by(|a, b| a.0.distance(p).total_cmp(&b.0.distance(p)))
}
/// Slide `q`, on the line through `at` along `dir` (beyond `at` only, for a `ray`), to where
/// the nearest target line or angled glyph guide crosses it, at most twice `tol` away: where it lands and the
/// target's own point (where its line starts).
fn slide(&self, at: Point, dir: Vec2, q: Point, tol: f64, ray: bool) -> Option<(Point, Point)> {
if !dir.hypot2().is_finite() || dir.hypot2() <= 1e-18 {
return None;
}
let reach = 2.0 * tol;
let mut best: Option<(f64, Point, Point)> = None;
for (vertical, lines, d, a, v) in [(true, &self.xs, dir.x, at.x, q.x), (false, &self.ys, dir.y, at.y, q.y)] {
if d.abs() <= 1e-9 {
continue;
}
// The ruler guides that way count as lines too (#812).
let rulers: Vec<(f64, Point, Kind)> = self.rulers.iter().filter(|r| r.vertical == vertical).filter_map(|r| r.line_at(q, reach)).collect();
// A line that far across the way crosses it at least that far along.
for (t, from, _) in lines_near(lines, v, reach).iter().chain(&rulers) {
let s = (t - a) / d;
// Exactly on the line, whatever the rounding along the way.
let hit = if vertical { Point::new(*t, at.y + dir.y * s) } else { Point::new(at.x + dir.x * s, *t) };
let moved = hit.distance(q);
if moved <= reach && (!ray || s > 0.0) && best.is_none_or(|b| moved < b.0) {
best = Some((moved, hit, *from));
}
}
}
// The angled glyph guides it crosses.
for &(on, e) in &self.angled {
let across = dir.cross(e);
if across.abs() <= 1e-9 * dir.hypot() {
continue;
}
let s = (on - at).cross(e) / across;
let hit = at + dir * s;
let moved = hit.distance(q);
if moved <= reach && (!ray || s > 0.0) && best.is_none_or(|b| moved < b.0) {
best = Some((moved, hit, on));
}
}
best.map(|(_, hit, from)| (hit, from))
}
/// The guides of a point `q` slid into line with the target at `from`: the line from it and
/// "align", or the target's own label when `q` sits right on it.
fn lined_up(&self, q: Point, from: Point) -> Vec<Overlay> {
if let Some((on, k)) = self.nearest_point(q, 1e-9) {
return self.label(on, k.label()).into_iter().collect();
}
self.line(from, q).into_iter().chain(self.label(q, "align")).collect()
}
/// A point `p` near no target anchor or center landed where two target paths cross
/// ("intersect"), else on the nearest target path ("path"), within `tol`: the point and its
/// label, as [`Self::snap_point`] lands it. The ruler guides of `rulers` count as paths that
/// cross ([`Self::rulers`]). None when no path is in reach, or the targets hold no segments.
pub(crate) fn snap_onto_path(&self, p: Point, tol: f64, rulers: Option<&Targets>) -> Option<(Point, Vec<Overlay>)> {
if self.segments.is_empty() {
return None;
}
if let Some(q) = self.crossing_with(p, tol, rulers.map_or(&self.rulers, |r| &r.rulers)) {
return Some((q, self.label(q, "intersect").into_iter().collect()));
}
let q = self.on_segment(p, tol)?;
Some((q, self.label(q, Kind::Edge.label()).into_iter().collect()))
}
/// [`Self::snap_onto_path`] for a selection held by a point `p` of a path's edge, its bounds
/// now `r` (#8568). Where paths cross, or on a curved segment, the point lands as
/// `snap_onto_path` lands it. On a straight segment, the selection then slides along that
/// segment, so the point stays on it, until its bounds line up with the other art or are spaced
/// evenly with it ([`Self::snap_rects_along`]), else until they line up with a ruler guide of
/// `rulers` ([`Self::snap_moved_along_to_rulers`]). A slide goes at most twice `tol` and not
/// past the segment's ends. Returns where the point goes and the guides.
pub(crate) fn snap_held_onto_path(&self, p: Point, r: Rect, tol: f64, rulers: Option<&Targets>) -> Option<(Point, Vec<Overlay>)> {
if self.segments.is_empty() {
return None;
}
if let Some(q) = self.crossing_with(p, tol, rulers.map_or(&self.rulers, |r| &r.rulers)) {
return Some((q, self.label(q, "intersect").into_iter().collect()));
}
let (seg, q) = self.nearest_segment(p, tol)?;
let on_path = |q: Point| self.label(q, Kind::Edge.label());
let Some(l) = straight(seg) else { return Some((q, on_path(q).into_iter().collect())) };
let len = (l.p1 - l.p0).hypot();
if !len.is_finite() || len <= 1e-9 {
return Some((q, on_path(q).into_iter().collect()));
}
let u = (l.p1 - l.p0) / len;
let moved = r + (q - p);
// How far the point may slide each way: twice `tol`, and not past the segment's ends.
let at = (q - l.p0).dot(u);
let within = ((-at).max(-2.0 * tol), (len - at).min(2.0 * tol));
let (s, mut ov) = Some(self.slide_rects_along(&[moved], u, tol, within))
.filter(|(.., hit)| *hit)
.or_else(|| rulers.map(|t| t.slide_moved_along_to_rulers(q, moved, u, tol, within)).filter(|(.., hit)| *hit))
.map_or((Vec2::ZERO, vec![]), |(s, ov, _)| (s, ov));
let q = q + s;
// The point's label is "path", the label a ruler guide's slide puts there too.
ov.retain(|o| !matches!(o, Overlay::Label { .. }));
ov.extend(on_path(q));
Some((q, ov))
}
/// The nearest point within `tol` of `p` on a target segment.
fn on_segment(&self, p: Point, tol: f64) -> Option<Point> {
self.nearest_segment(p, tol).map(|(_, q)| q)
}
/// [`Self::on_segment`], with the segment the point is on.
fn nearest_segment(&self, p: Point, tol: f64) -> Option<(PathSeg, Point)> {
self.segments
.iter()
.filter(|(b, _)| b.inflate(tol, tol).contains(p))
.map(|(_, c)| (c, c.nearest(p, 1e-6)))
.filter(|(_, n)| n.distance_sq <= tol * tol)
.min_by(|a, b| a.1.distance_sq.total_cmp(&b.1.distance_sq))
.map(|(c, n)| (*c, c.eval(n.t)))
}
/// Where two target paths, a path and a ruler guide, or two ruler guides cross, the crossing
/// nearest `p` within `tol` ("intersect", #1602).
pub(super) fn crossing(&self, p: Point, tol: f64) -> Option<Point> {
self.crossing_with(p, tol, &self.rulers)
}
/// [`Self::crossing`] with the ruler guides `rulers`.
fn crossing_with(&self, p: Point, tol: f64, rulers: &[Ruler]) -> Option<Point> {
// A ruler guide running past, as a short line through the reach of `p`.
let ruler = |r: &Ruler| {
let (pos, ..) = r.line_at(p, tol)?;
let (across, along) = if r.vertical { (p.x, p.y) } else { (p.y, p.x) };
let (a, b) = (along - tol, along + tol);
((pos - across).abs() <= tol)
.then(|| PathSeg::Line(if r.vertical { Line::new((pos, a), (pos, b)) } else { Line::new((a, pos), (b, pos)) }))
};
let near: Vec<PathSeg> = self
.segments
.iter()
.filter(|(b, c)| b.inflate(tol, tol).contains(p) && c.nearest(p, 1e-6).distance_sq <= tol * tol)
.map(|(_, c)| *c)
.chain(rulers.iter().filter_map(ruler))
// shortcut: the first 32 lines in reach are paired, raise it if busier crossings matter
.take(32)
.collect();
let mut best: Option<Point> = None;
for (i, a) in near.iter().enumerate() {
for b in near.iter().skip(i + 1) {
let hits: Vec<Point> = match (a, b) {
(PathSeg::Line(l), c) | (c, PathSeg::Line(l)) => c.intersect_line(*l).iter().map(|x| l.eval(x.line_t)).collect(),
_ => meeting(a, b, p).into_iter().collect(),
};
for q in hits {
if q.distance(p) <= tol && best.is_none_or(|b| q.distance(p) < b.distance(p)) {
best = Some(q);
}
}
}
}
best
}
/// Snap a ruler guide at `v` (the x of a vertical one, the y of a horizontal one) into line
/// with the nearest edge, centre or anchor within `tol`: where it goes, and a label there.
pub fn snap_guide(&self, vertical: bool, v: f64, tol: f64) -> (f64, Vec<Overlay>) {
let along = |q: &Point| if vertical { q.x } else { q.y };
let lines = if vertical { &self.xs } else { &self.ys };
let best = lines_near(lines, v, tol)
.iter()
.map(|(t, from, k)| (*t, *from, *k))
.chain(self.points.iter().map(|(q, k)| (along(q), *q, *k)))
.filter(|(t, ..)| (t - v).abs() <= tol)
.min_by(|a, b| (a.0 - v).abs().total_cmp(&(b.0 - v).abs()));
match best {
Some((t, from, k)) => (t, self.label(from, k.label()).into_iter().collect()),
None => (v, vec![]),
}
}
/// Snap a dragged point that carries others along at `offsets` (a resize handle and the
/// bleed edge beyond it): onto an anchor or centre near the point itself, otherwise into line
/// with targets, each axis on whichever of them comes nearest.
pub fn snap_point_with(&self, p: Point, offsets: &[Vec2], tol: f64) -> (Point, Vec<Overlay>) {
if self.nearest_point(p, tol).is_some() {
return self.snap_point(p, tol);
}
let rects: Vec<Rect> = std::iter::once(Vec2::ZERO).chain(offsets.iter().copied()).map(|o| Rect::from_points(p + o, p + o)).collect();
let (adj, mut ov, aligned) = self.align_rects(&rects, tol);
let out = p + adj;
if aligned.contains(&true) {
ov.extend(self.label(out, "align"));
}
(out, ov)
}
/// Snap a moving rectangle (selection bounds after a move by `d`): tries its corners/edges/centre.
pub fn snap_rect(&self, r: Rect, tol: f64) -> (Vec2, Vec<Overlay>) {
self.snap_rects(&[r], tol)
}
/// Snap a point that may only move along `dir` (the grabbed point of a move Shift keeps to its
/// line): onto the point of that line nearest an anchor or center within `tol` of `p`, labeled
/// at the anchor or center, else to where the nearest target line or ruler guide crosses the
/// line, at most twice `tol` away ([`Self::slide`]). Returns where it goes and the guides.
pub(crate) fn snap_point_along(&self, p: Point, dir: Vec2, tol: f64) -> (Point, Vec<Overlay>) {
let l2 = dir.hypot2();
if !l2.is_finite() || l2 <= 1e-18 {
return (p, vec![]);
}
if let Some((q, k)) = self.nearest_point(p, tol) {
return (p + dir * ((q - p).dot(dir) / l2), self.label(q, k.label()).into_iter().collect());
}
match self.slide(p, dir, p, tol, false) {
Some((q, from)) => (q, self.lined_up(q, from)),
None => (p, vec![]),
}
}
/// [`Self::snap_rects`] for rectangles that may only move along `dir` (a move Shift keeps to
/// its line): they slide along it until the edge or center of one of them is in line with a
/// target, within `tol` of it on that axis, the target that needs the shortest way along the
/// line winning. Lining up with nothing, a single rectangle with Spacing Guides slides to where
/// it is spaced evenly along an axis the line runs along. Returns the shift (along `dir`) and
/// the guides.
pub(crate) fn snap_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64) -> (Vec2, Vec<Overlay>) {
let (s, ov, _) = self.slide_rects_along(rects, dir, tol, (f64::NEG_INFINITY, f64::INFINITY));
(s, ov)
}
/// [`Self::snap_rects_along`] for a slide of `within` (the least and the most way along
/// `dir`), also saying whether anything lined up or was spaced evenly.
fn slide_rects_along(&self, rects: &[Rect], dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec<Overlay>, bool) {
let len = dir.hypot();
if !len.is_finite() || len <= 1e-9 {
return (Vec2::ZERO, vec![], false);
}
let u = dir / len;
// The axes the line runs along: the x axis (`true`) and the y axis, and how far a step of
// one along the line goes on that axis.
let axes = [(true, u.x), (false, u.y)].into_iter().filter(|(_, c)| c.abs() > 1e-9);
// The way along the line, the target line it lines up with, where that line starts, and
// its axis.
let mut best: Option<(f64, f64, Point, bool)> = None;
for (x, c) in axes.clone() {
let lines = if x { &self.xs } else { &self.ys };
for r in rects {
let vs = if x { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] };
for v in vs {
for (t, from, _) in lines_near(lines, v, tol).iter().filter(|(t, ..)| (t - v).abs() <= tol) {
let s = (t - v) / c;
if (lo..=hi).contains(&s) && best.is_none_or(|b| s.abs() < b.0.abs()) {
best = Some((s, *t, *from, x));
}
}
}
}
}
if let Some((s, t, from, x)) = best {
let ov = rects.iter().map(|r| *r + u * s).reduce(|a, b| a.union(b)).and_then(|m| {
if x {
self.line(Point::new(t, from.y.min(m.y0)), Point::new(t, from.y.max(m.y1)))
} else {
self.line(Point::new(from.x.min(m.x0), t), Point::new(from.x.max(m.x1), t))
}
});
return (u * s, ov.into_iter().collect(), true);
}
let [r] = rects else { return (Vec2::ZERO, vec![], false) };
if self.boxes.is_empty() {
return (Vec2::ZERO, vec![], false);
}
// The slide that spaces it evenly along each axis, within `lo..=hi` along the line. A slide
// along a slanted line also moves it across, so the gaps must still be equal where it ends
// up.
let spaced = axes
.filter_map(|(x, c)| {
// A level or upright slide along that axis keeps its row.
let level = (if x { u.y } else { u.x }).abs() <= 1e-9;
// At most 8 slides are checked where they end up, to bound the work per pointer move.
let checked = std::cell::Cell::new(0_usize);
let fits = |shift: f64| {
let s = shift / c;
if !(lo..=hi).contains(&s) {
return false;
}
if level {
return true;
}
if checked.get() >= 8 {
return false;
}
checked.set(checked.get() + 1);
self.even_spacing(*r + u * s, x, tol).is_some_and(|(rest, _)| rest.abs() <= 1e-6)
};
self.even_spacing_by(*r, x, tol, Some(&fits)).map(|(shift, _)| (shift / c, x))
})
.min_by(|a, b| a.0.abs().total_cmp(&b.0.abs()));
let Some((s, x)) = spaced else { return (Vec2::ZERO, vec![], false) };
let gaps = self.even_spacing(*r + u * s, x, tol).map(|(_, gaps)| gaps).unwrap_or_default();
(u * s, gaps.into_iter().flat_map(|g| self.gap_marks(g, x, tol)).collect(), true)
}
/// Snap rectangles that move together (an artboard and its bleed): the edge or centre of any
/// of them nearest a target, per axis. A single moved selection with Spacing Guides
/// ([`Self::for_move`]) is spaced evenly along an axis that lines up with nothing
/// ([`Self::even_spacing`]). Returns the shift and the guides.
pub fn snap_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec<Overlay>) {
let (d, ov, _) = self.snap_rects_axes(rects, tol);
(d, ov)
}
/// [`Self::snap_rects`], also saying which axes (x, y) lined up or were spaced evenly.
pub(crate) fn snap_rects_axes(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec<Overlay>, [bool; 2]) {
let (mut d, mut ov, aligned) = self.align_rects(rects, tol);
let mut taken = aligned;
if let [r] = rects
&& !self.boxes.is_empty()
{
let moved = *r + d;
let mut spaced = false;
for (x, lined_up) in [true, false].into_iter().zip(aligned) {
if let Some((shift, _)) = self.even_spacing(moved, x, tol).filter(|_| !lined_up) {
*(if x { &mut d.x } else { &mut d.y }) += shift;
taken[usize::from(!x)] = true;
spaced = true;
}
}
// The equal gaps, marked where the rectangle ends up.
if spaced {
let done = *r + d;
for (x, lined_up) in [true, false].into_iter().zip(aligned) {
let gaps = if lined_up { None } else { self.even_spacing(done, x, tol) };
ov.extend(gaps.into_iter().flat_map(|(_, gaps)| gaps).flat_map(|g| self.gap_marks(g, x, tol)));
}
}
}
(d, ov, taken)
}
/// Spacing Guides along the x axis (`x`) or the y axis for the moved rectangle `r`, among the
/// objects of its row (column): the shift (within `tol`) that leaves it as far from its
/// neighbour before or after it as two other objects of the row are apart, or as far from both
/// neighbours; and the equal gaps then, as (start, end, where across) along that axis.
fn even_spacing(&self, r: Rect, x: bool, tol: f64) -> Option<(f64, Vec<[f64; 3]>)> {
self.even_spacing_by(r, x, tol, None)
}
/// [`Self::even_spacing`] for the nearest shift along that axis that `accept` takes (any shift
/// when `None`).
fn even_spacing_by(&self, r: Rect, x: bool, tol: f64, accept: Option<&dyn Fn(f64) -> bool>) -> Option<(f64, Vec<[f64; 3]>)> {
let (r0, r1) = span(&r, x);
let len = r1 - r0;
let (c0, c1) = span(&r, !x);
// The objects beside it, before or after, overlapping it across, by where they start.
let mut row: Vec<(Rect, f64, f64)> = self
.boxes
.iter()
.map(|b| (*b, span(b, x).0, span(b, x).1))
.filter(|(b, a0, a1)| span(b, !x).0 < c1 && span(b, !x).1 > c0 && (*a1 <= r0 + tol || *a0 >= r1 - tol))
.collect();
row.sort_by(|a, b| a.1.total_cmp(&b.1));
// Where two boxes overlap across: the middle of that (or of the space between them).
let mid = |a: &Rect, b: &Rect| (span(a, !x).0.max(span(b, !x).0) + span(a, !x).1.min(span(b, !x).1)) / 2.0;
// Each object and the nearest one after it, unless the moved rectangle sits between them.
let pairs: Vec<(f64, [f64; 3])> = row
.iter()
.filter_map(|(p, _, p1)| {
let next = row.partition_point(|(_, a0, _)| *a0 < *p1);
let (q, q0, _) = row.get(next)?;
let straddles = *p1 <= r0 + tol && *q0 >= r1 - tol;
(*q0 > *p1 && !straddles).then(|| (q0 - p1, [*p1, *q0, mid(p, q)]))
})
.collect();
let before = row.iter().filter(|(_, _, a1)| *a1 <= r0 + tol).max_by(|a, b| a.2.total_cmp(&b.2));
let after = row.iter().filter(|(_, a0, _)| *a0 >= r1 - tol).min_by(|a, b| a.1.total_cmp(&b.1));
// Where it could start, and the gap it repeats (None: halfway between its neighbours).
let mut starts: Vec<(f64, Option<f64>)> = vec![];
if let (Some(a), Some(b)) = (before, after)
&& b.1 - a.2 > len
{
starts.push(((a.2 + b.1 - len) / 2.0, None));
}
for (g, _) in &pairs {
starts.extend(before.map(|a| (a.2 + g, Some(*g))));
starts.extend(after.map(|b| (b.1 - g - len, Some(*g))));
}
starts.retain(|(t, _)| (t - r0).abs() <= tol);
let nearer = |a: &(f64, Option<f64>), b: &(f64, Option<f64>)| (a.0 - r0).abs().total_cmp(&(b.0 - r0).abs());
let (start, repeats) = match accept {
// The nearest start, the first proposed among equally near ones.
None => starts.into_iter().min_by(nearer)?,
Some(accept) => {
// Nearest first; the sort is stable, so equally near starts keep the order they
// were proposed in. Starts as near as each other are at most two shifts (one each
// way), so the shifts refused at the current distance are few, and each is asked
// about once.
starts.sort_by(nearer);
let mut refused: Vec<f64> = vec![];
let mut at = f64::NAN;
starts.into_iter().find(|(t, _)| {
let shift = t - r0;
if shift.abs() != at {
at = shift.abs();
refused.clear();
}
if refused.contains(&shift) {
return false;
}
let ok = accept(shift);
if !ok {
refused.push(shift);
}
ok
})?
}
};
let at = r + if x { Vec2::new(start - r0, 0.0) } else { Vec2::new(0.0, start - r0) };
let (end, mut gaps) = (start + len, vec![]);
if let Some((a, _, a1)) = before
&& repeats.is_none_or(|g| (start - a1 - g).abs() <= 1e-9)
{
gaps.push([*a1, start, mid(a, &at)]);
}
if let Some((b, b0, _)) = after
&& repeats.is_none_or(|g| (b0 - end - g).abs() <= 1e-9)
{
gaps.push([end, *b0, mid(b, &at)]);
}
if let Some(g) = repeats {
gaps.extend(pairs.iter().filter(|(pg, _)| (pg - g).abs() <= 1e-9).map(|(_, gap)| *gap));
}
Some((start - r0, gaps))
}
/// A Spacing Guides mark: a line across the gap (start, end, where across) along the x axis
/// (`x`) or the y axis, with a tick `tick` long either side of it at each end.
fn gap_marks(&self, [u0, u1, c]: [f64; 3], x: bool, tick: f64) -> [Overlay; 3] {
let pt = |u: f64, c: f64| if x { Point::new(u, c) } else { Point::new(c, u) };
let line = |a: Point, b: Point| Overlay::Line { a, b, color: self.style.color, dashed: false };
[line(pt(u0, c), pt(u1, c)), line(pt(u0, c - tick), pt(u0, c + tick)), line(pt(u1, c - tick), pt(u1, c + tick))]
}
/// [`Self::snap_rects`] before Spacing Guides, also saying whether each axis (x, y) lined up
/// (even with Alignment Guides off, or already in line, when there is no line or shift to
/// tell).
fn align_rects(&self, rects: &[Rect], tol: f64) -> (Vec2, Vec<Overlay>, [bool; 2]) {
let nearest = |targets: &[(f64, Point, Kind)], along: fn(&Rect) -> [f64; 3]| {
rects
.iter()
.flat_map(|r| along(r).into_iter().map(move |v| (v, *r)))
.flat_map(|(v, r)| lines_near(targets, v, tol).iter().map(move |(t, from, _)| (t - v, *from, v, r)))
.filter(|(d, ..)| d.abs() <= tol)
.min_by(|a, b| a.0.abs().total_cmp(&b.0.abs()))
};
let best_x = nearest(&self.xs, |r| [r.x0, r.center().x, r.x1]);
let best_y = nearest(&self.ys, |r| [r.y0, r.center().y, r.y1]);
let mut d = Vec2::ZERO;
let mut ov = vec![];
if let Some((dx, from, x, r)) = best_x {
d.x = dx;
let x = x + dx;
let (y0, y1) = (from.y.min(r.y0), from.y.max(r.y1));
ov.extend(self.line(Point::new(x, y0), Point::new(x, y1)));
}
if let Some((dy, from, y, r)) = best_y {
d.y = dy;
let y = y + dy;
let (x0, x1) = (from.x.min(r.x0), from.x.max(r.x1));
ov.extend(self.line(Point::new(x0, y), Point::new(x1, y)));
}
(d, ov, [best_x.is_some(), best_y.is_some()])
}
/// Snap a selection grabbed at `p` and moved as a whole, its bounds now `r`, to the ruler
/// guides: the grabbed point goes into line with a guide running within `tol` of it
/// ([`Self::snap_point`]), and on an axis where none does and that is not `taken` (x, y)
/// already, the edge or centre of `r` nearest a guide running past it within `tol` goes onto it
/// (#5746). Returns the shift, the guides (none when nothing lines up) and whether a guide held
/// the grabbed point.
pub(crate) fn snap_moved_to_rulers(&self, p: Point, r: Option<Rect>, tol: f64, taken: [bool; 2]) -> (Vec2, Vec<Overlay>, bool) {
let near = |vertical: bool| {
let v = if vertical { p.x } else { p.y };
self.rulers.iter().any(|g| g.vertical == vertical && (g.pos - v).abs() <= tol && g.line_at(p, tol).is_some())
};
let held = [near(true), near(false)];
let (q, mut ov) = if held.contains(&true) { self.snap_point(p, tol) } else { (p, vec![]) };
let mut d = q - p;
let Some(r) = r.map(|r| r + d) else { return (d, ov, held.contains(&true)) };
// The guide upright (`vertical`) or level nearest one of `vs`, running past `r` across.
let nearest = |vertical: bool, vs: [f64; 3]| {
let (c, half) =
if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) };
self.rulers
.iter()
.filter(|g| g.vertical == vertical)
.filter_map(|g| g.line_at(c, tol + half))
.flat_map(|(t, from, _)| vs.into_iter().map(move |v| (t - v, t, from)))
.filter(|(s, ..)| s.abs() <= tol)
.min_by(|a, b| a.0.abs().total_cmp(&b.0.abs()))
};
let hx = if held[0] || taken[0] { None } else { nearest(true, [r.x0, r.center().x, r.x1]) };
let hy = if held[1] || taken[1] { None } else { nearest(false, [r.y0, r.center().y, r.y1]) };
let shift = Vec2::new(hx.map_or(0.0, |h| h.0), hy.map_or(0.0, |h| h.0));
let (r, lined) = (r + shift, hx.is_some() || hy.is_some());
d += shift;
if let Some((_, x, from)) = hx {
ov.extend(self.line(Point::new(x, from.y.min(r.y0)), Point::new(x, from.y.max(r.y1))));
}
if let Some((_, y, from)) = hy {
ov.extend(self.line(Point::new(from.x.min(r.x0), y), Point::new(from.x.max(r.x1), y)));
}
if lined && !held.contains(&true) {
ov.extend(self.label(p + d, "align"));
}
(d, ov, held.contains(&true))
}
/// [`Self::snap_moved_to_rulers`] for a selection a move Shift keeps to its line (through the
/// grabbed point `p`, along `dir`), its bounds now `r`: the edge or centre of `r` that a ruler
/// guide runs past within `tol` goes onto it by sliding along the line, the way needing the
/// shortest slide winning and at most twice `tol` (a line nearly parallel to a guide would
/// carry the selection far to meet it). Returns the shift along the line and the guides.
pub(crate) fn snap_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64) -> (Vec2, Vec<Overlay>) {
let (s, ov, _) = self.slide_moved_along_to_rulers(p, r, dir, tol, (f64::NEG_INFINITY, f64::INFINITY));
(s, ov)
}
/// [`Self::snap_moved_along_to_rulers`] for a slide of `within` (the least and the most way
/// along `dir`), also saying whether the bounds lined up with a guide.
fn slide_moved_along_to_rulers(&self, p: Point, r: Rect, dir: Vec2, tol: f64, (lo, hi): (f64, f64)) -> (Vec2, Vec<Overlay>, bool) {
let len = dir.hypot();
if !len.is_finite() || len <= 1e-9 {
return (Vec2::ZERO, vec![], false);
}
let u = dir / len;
// The way along the line, where the guide is and where it starts, and whether it is upright.
let mut best: Option<(f64, f64, Point, bool)> = None;
for (vertical, c) in [(true, u.x), (false, u.y)] {
if c.abs() <= 1e-9 {
continue;
}
let vs = if vertical { [r.x0, r.center().x, r.x1] } else { [r.y0, r.center().y, r.y1] };
let (mid, half) =
if vertical { (Point::new(0.0, r.center().y), r.height() / 2.0) } else { (Point::new(r.center().x, 0.0), r.width() / 2.0) };
for g in self.rulers.iter().filter(|g| g.vertical == vertical) {
for v in vs {
let s = (g.pos - v) / c;
if (g.pos - v).abs() > tol || s.abs() > 2.0 * tol || !(lo..=hi).contains(&s) || best.is_some_and(|b| s.abs() >= b.0.abs()) {
continue;
}
// The guide runs past the bounds: for a slide held to `within`, where the slide
// puts them; for a Shift move, where the move put them.
let at = if lo.is_finite() || hi.is_finite() { r.center() + u * s } else { mid };
if let Some((t, from, _)) = g.line_at(at, tol + half) {
best = Some((s, t, from, vertical));
}
}
}
}
let Some((s, t, from, vertical)) = best else { return (Vec2::ZERO, vec![], false) };
let moved = r + u * s;
let line = if vertical {
self.line(Point::new(t, from.y.min(moved.y0)), Point::new(t, from.y.max(moved.y1)))
} else {
self.line(Point::new(from.x.min(moved.x0), t), Point::new(from.x.max(moved.x1), t))
};
let mut ov: Vec<Overlay> = line.into_iter().collect();
ov.extend(self.label(p + u * s, "align"));
(u * s, ov, true)
}
/// Snap a bounding-box resize. `a` is the scale [`crate::bbox::scale_for_drag`] gave for
/// dragging `handle` of the box `bx` (about the centre when `from_center`), in the box's own
/// frame, and so is the result. The handle lands on an anchor or centre within `tol` on the page
/// (labelled as [`Self::snap_point`] does), else the corners and the side it moves line up with
/// the nearest target or ruler guide ("align"), whatever the box's angle. A handle with one way
/// to go (a side, or a proportional corner) slides along it until one of them is on a target.
pub fn snap_scale(&self, bx: &OrientedBox, handle: Handle, a: Affine, proportional: bool, from_center: bool, tol: f64) -> (Affine, Vec<Overlay>) {
type Hit = Option<(f64, Point)>;
// Where a snap lands: in line with a target's x and/or y, or on an anchor or centre.
type Snap = (Hit, Hit, Option<(Point, Kind)>);
let r = bx.rect;
let origin = if from_center { r.center() } else { handle.opposite().pos(r) };
let (d0, [sx, _, _, sy, _, _]) = (handle.pos(r) - origin, a.as_coeffs());
let (to_doc, to_local) = (bx.to_doc(), bx.to_doc().inverse());
// A scale that collapses or flips the box is no snap.
let valid = |n: f64, s: f64| n.is_finite() && n * s > 0.0;
// The target line along the x axis (`x`: a vertical line) or the y axis nearest `p`, the
// ruler guides running past it included.
let nearest = |p: Point, x: bool| -> Hit {
let (v, ts) = if x { (p.x, &self.xs) } else { (p.y, &self.ys) };
let rulers = self.rulers.iter().filter(|r| r.vertical == x).filter_map(|r| r.line_at(p, tol));
lines_near(ts, v, tol)
.iter()
.copied()
.chain(rulers)
.map(|(t, from, _)| (t, from))
.filter(|(t, _)| (t - v).abs() <= tol)
.min_by(|p, q| (p.0 - v).abs().total_cmp(&(q.0 - v).abs()))
};
let (mut nx, mut ny) = (sx, sy);
let mut snap: Snap = (None, None, None);
if handle.is_corner() && !proportional {
// The corner goes anywhere: onto an anchor or centre, else it takes the target's x, its
// y, or both.
let p = to_doc * (a * handle.pos(r));
let (hx, hy) = (nearest(p, true), nearest(p, false));
let on = self.nearest_point(p, tol).map(|(q, k)| (Some((q.x, q)), Some((q.y, q)), Some((q, k))));
for (tx, ty, at) in on.into_iter().chain([(hx, hy, None), (hx, None, None), (None, hy, None)]) {
if tx.is_none() && ty.is_none() {
continue;
}
let q = to_local * Point::new(tx.map_or(p.x, |h| h.0), ty.map_or(p.y, |h| h.0));
let (mut cx, mut cy) = ((q.x - origin.x) / d0.x, (q.y - origin.y) / d0.y);
// Square to the page, the axis without a target stays exactly where it was.
if bx.angle == 0.0 {
(cx, cy) = (if tx.is_some() { cx } else { sx }, if ty.is_some() { cy } else { sy });
}
if valid(cx, sx) && valid(cy, sy) {
(nx, ny, snap) = (cx, cy, (tx, ty, at));
break;
}
}
} else {
// One parameter `s`: the scale is `c + sĀ·e` on each axis.
let (ax, _) = handle.axes();
let (e, c, s0) = match (handle.is_corner(), ax, proportional) {
(true, _, _) => ((sx.signum(), sy.signum()), (0.0, 0.0), sx.abs()),
(false, true, true) => ((1.0, sx.signum()), (0.0, 0.0), sx),
(false, true, false) => ((1.0, 0.0), (0.0, 1.0), sx),
(false, false, true) => ((sy.signum(), 1.0), (0.0, 0.0), sy),
(false, false, false) => ((0.0, 1.0), (1.0, 0.0), sy),
};
// The points that may land on a target: the handle, and the two ends of its side.
let i = handle as usize;
let ends = if handle.is_corner() { [None, None] } else { [Handle::ALL.get((i + 1) % 8), Handle::ALL.get((i + 7) % 8)] };
// How far the handle travels per unit of `s`: a snap may not drag it far from the
// pointer, as it would for a target the side runs almost along.
let travel = (e.0 * d0.x).hypot(e.1 * d0.y);
// The snap so far: its `s`, whether it only lines up (an anchor or centre comes first),
// how far it moves the handle, and where it lands.
let mut best: Option<(f64, bool, f64, Snap)> = None;
let mut consider = |s: f64, in_line: bool, found: Snap| {
let moved = (s - s0).abs() * travel;
if valid(s, s0) && moved <= 2.0 * tol && best.as_ref().is_none_or(|k| (in_line, moved) < (k.1, k.2)) {
best = Some((s, in_line, moved, found));
}
};
for h in std::iter::once(handle).chain(ends.into_iter().flatten().copied()) {
let v = h.pos(r) - origin;
let base = to_doc * (origin + Vec2::new(c.0 * v.x, c.1 * v.y));
let dir = (to_doc * Point::new(e.0 * v.x, e.1 * v.y)).to_vec2();
let p = base + dir * s0;
// An anchor or centre beside its way: it stops at the nearest point of the way.
let l2 = dir.hypot2();
if l2 > 1e-18
&& let Some((q, k)) = self.nearest_point(p, tol)
{
consider((q - base).dot(dir) / l2, false, (None, None, Some((q, k))));
}
for (is_x, b, d) in [(true, base.x, dir.x), (false, base.y, dir.y)] {
if d.abs() <= 1e-9 {
continue;
}
let Some(hit) = nearest(p, is_x) else { continue };
consider((hit.0 - b) / d, true, if is_x { (Some(hit), None, None) } else { (None, Some(hit), None) });
}
}
if let Some((s, _, _, found)) = best {
(nx, ny, snap) = (c.0 + s * e.0, c.1 + s * e.1, found);
}
}
let mut out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2());
let (hit_x, hit_y, on) = snap;
if let Some((q, k)) = on {
return (out, self.label(q, k.label()).into_iter().collect());
}
// The lines run from the target's own point across the resized box, on the page.
let mut nr = (to_doc * out).transform_rect_bbox(r);
let mut ov = vec![];
if let Some((x, from)) = hit_x {
ov.extend(self.line(Point::new(x, from.y.min(nr.y0)), Point::new(x, from.y.max(nr.y1))));
}
if let Some((y, from)) = hit_y {
ov.extend(self.line(Point::new(from.x.min(nr.x0), y), Point::new(from.x.max(nr.x1), y)));
}
if hit_x.is_some() || hit_y.is_some() {
ov.extend(self.label(to_doc * (out * handle.pos(r)), "align"));
}
if !self.boxes.is_empty() && !from_center {
let aligned = [hit_x.is_some(), hit_y.is_some()];
for (is_x, lined_up) in [(true, aligned[0]), (false, aligned[1])] {
if lined_up {
continue;
}
let Some(moves_min) = resize_moves_min_edge(handle, is_x) else { continue };
if let Some((shift, gaps)) = self.even_spacing(nr, is_x, tol) {
let (lo, hi) = span(&nr, is_x);
let len = hi - lo;
let new_len = if moves_min { hi - (lo + shift) } else { hi + shift - lo };
if len > 1e-9 && new_len > 1e-9 {
let f = new_len / len;
let (ax, ay) = handle.axes();
if is_x {
nx *= f;
if proportional && ay {
ny *= f;
}
} else {
ny *= f;
if proportional && ax {
nx *= f;
}
}
out = Affine::translate(origin.to_vec2()) * Affine::scale_non_uniform(nx, ny) * Affine::translate(-origin.to_vec2());
nr = (to_doc * out).transform_rect_bbox(r);
ov.extend(gaps.into_iter().flat_map(|g| self.gap_marks(g, is_x, tol)));
}
}
}
}
(out, ov)
}
}
No file is open. Choose one in the tree, or press Ctrl+O (āO on a Mac) to find one by name.
Syntax highlighting could not load. The unmodified read-only text remains available above.