Skip to main content

egui_pop_viewport/
overlay.rs

1//! Overlays in image coordinates, edited through one handle kit.
2//!
3//! <div class="warning">Experimental: may change in any release
4//! (docs/stability.md).</div>
5//!
6//! The application owns its overlays (shapes, guides, a crop box) and
7//! gives them to the viewport each frame; the viewport draws them and
8//! turns drags on their handles into [`Signal::Handle`](crate::Signal)s
9//! (begin, update, end, or cancel on Escape), which the application
10//! applies to its own data ([`Overlay::apply`] does it for the standard
11//! shapes). A `before_handle` hook may veto a move or snap it.
12//!
13//! The same handle kinds look and behave the same everywhere: a body
14//! (move), points and corners, edges, a size, a rotation, a feather, a
15//! Bézier control. Their hit target is [`HIT_RADIUS`] points whatever
16//! their drawn size. A click on a handle, or on an overlay's outline away
17//! from its handles (to add a point there), is a signal too.
18//!
19//! Each overlay has a [`Style`]: an emphasis (normal, selected, faint)
20//! and a dashed line; shapes are points, lines, boxes, circles, ellipses
21//! and paths.
22
23use egui::{Color32, Painter, Pos2, Stroke, StrokeKind, vec2};
24
25use crate::tokens::ViewportTokens;
26use crate::view::Mapping;
27
28/// The radius of a handle's hit target, in points (24-point targets).
29pub const HIT_RADIUS: f32 = 12.0;
30
31/// The radius a handle is drawn with, in points.
32pub const DRAWN_RADIUS: f32 = 5.0;
33
34/// A shape's line, its dark outline under it, a handle's outline, in
35/// points before snapping: each is drawn as whole physical pixels at the
36/// window's scale (`scale::stroke`), so it never blurs at 125 % or 150 %.
37pub const LINE_WIDTH: f32 = 1.5;
38pub const UNDER_WIDTH: f32 = 3.0;
39pub const OUTLINE_WIDTH: f32 = 1.5;
40
41/// A width of `w` points, snapped to whole pixels where `painter` draws.
42fn snapped(painter: &Painter, w: f32) -> f32 {
43    egui_pop_core::scale::stroke(painter.ctx(), w)
44}
45
46/// What a handle adjusts.
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum HandleKind {
49    /// The whole shape (its body).
50    Move,
51    /// One point of a line or a path.
52    Point,
53    /// A corner of a box.
54    Corner,
55    /// An edge of a box.
56    Edge,
57    /// A size (a radius).
58    Size,
59    /// A rotation.
60    Rotate,
61    /// A feather (a soft edge).
62    Feather,
63    /// A Bézier control point: the end of a curve's tangent at a point.
64    Control,
65}
66
67impl HandleKind {
68    pub fn name(self) -> &'static str {
69        match self {
70            HandleKind::Move => "move",
71            HandleKind::Point => "point",
72            HandleKind::Corner => "corner",
73            HandleKind::Edge => "edge",
74            HandleKind::Size => "size",
75            HandleKind::Rotate => "rotate",
76            HandleKind::Feather => "feather",
77            HandleKind::Control => "control",
78        }
79    }
80}
81
82/// A handle: an index within its overlay, a kind, a place (image
83/// pixels).
84#[derive(Clone, Copy, Debug, PartialEq)]
85pub struct Handle {
86    pub index: u32,
87    pub kind: HandleKind,
88    pub at: [f64; 2],
89}
90
91/// A shape in image pixels.
92#[derive(Clone, Debug, PartialEq)]
93pub enum Shape {
94    Point([f64; 2]),
95    Line([f64; 2], [f64; 2]),
96    /// `[x0, y0, x1, y1]`.
97    Rect([f64; 4]),
98    Circle {
99        center: [f64; 2],
100        radius: f64,
101    },
102    /// An ellipse: its radii along its own axes, turned by `rotation`
103    /// (radians, clockwise on screen).
104    Ellipse {
105        center: [f64; 2],
106        radii: [f64; 2],
107        rotation: f64,
108    },
109    Path {
110        points: Vec<[f64; 2]>,
111        closed: bool,
112    },
113}
114
115impl Shape {
116    /// The standard handles of the shape.
117    pub fn handles(&self) -> Vec<Handle> {
118        let h = |index, kind, at| Handle { index, kind, at };
119        match self {
120            Shape::Point(p) => vec![h(0, HandleKind::Move, *p)],
121            Shape::Line(a, b) => vec![
122                h(0, HandleKind::Point, *a),
123                h(1, HandleKind::Point, *b),
124                h(2, HandleKind::Move, mid(*a, *b)),
125            ],
126            Shape::Rect(r) => {
127                let [x0, y0, x1, y1] = *r;
128                let (mx, my) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
129                vec![
130                    h(0, HandleKind::Corner, [x0, y0]),
131                    h(1, HandleKind::Corner, [x1, y0]),
132                    h(2, HandleKind::Corner, [x1, y1]),
133                    h(3, HandleKind::Corner, [x0, y1]),
134                    h(4, HandleKind::Edge, [mx, y0]),
135                    h(5, HandleKind::Edge, [x1, my]),
136                    h(6, HandleKind::Edge, [mx, y1]),
137                    h(7, HandleKind::Edge, [x0, my]),
138                    h(8, HandleKind::Move, [mx, my]),
139                ]
140            }
141            Shape::Circle { center, radius } => vec![
142                h(0, HandleKind::Move, *center),
143                h(1, HandleKind::Size, [center[0] + radius, center[1]]),
144            ],
145            Shape::Ellipse {
146                center,
147                radii,
148                rotation,
149            } => {
150                let at = |x: f64, y: f64| along(*center, *rotation, x, y);
151                vec![
152                    h(0, HandleKind::Move, *center),
153                    h(1, HandleKind::Size, at(radii[0], 0.0)),
154                    h(2, HandleKind::Size, at(0.0, radii[1])),
155                    h(3, HandleKind::Rotate, at(0.0, -radii[1] * ROTATE_OUT)),
156                ]
157            }
158            Shape::Path { points, .. } => {
159                let mut v: Vec<Handle> = points
160                    .iter()
161                    .enumerate()
162                    .map(|(i, p)| h(i as u32, HandleKind::Point, *p))
163                    .collect();
164                if !points.is_empty() {
165                    let n = points.len() as f64;
166                    let c = points
167                        .iter()
168                        .fold([0.0, 0.0], |a, p| [a[0] + p[0] / n, a[1] + p[1] / n]);
169                    v.push(h(points.len() as u32, HandleKind::Move, c));
170                }
171                v
172            }
173        }
174    }
175
176    /// The shape after handle `index` moved from `from` to `to` (image
177    /// pixels), starting from this shape (the one at the gesture's
178    /// start).
179    pub fn moved(&self, index: u32, from: [f64; 2], to: [f64; 2]) -> Shape {
180        let d = [to[0] - from[0], to[1] - from[1]];
181        let shift = |p: [f64; 2]| [p[0] + d[0], p[1] + d[1]];
182        match self {
183            Shape::Point(p) => Shape::Point(shift(*p)),
184            Shape::Line(a, b) => match index {
185                0 => Shape::Line(to, *b),
186                1 => Shape::Line(*a, to),
187                _ => Shape::Line(shift(*a), shift(*b)),
188            },
189            Shape::Rect(r) => {
190                let [mut x0, mut y0, mut x1, mut y1] = *r;
191                match index {
192                    0 => (x0, y0) = (to[0], to[1]),
193                    1 => (x1, y0) = (to[0], to[1]),
194                    2 => (x1, y1) = (to[0], to[1]),
195                    3 => (x0, y1) = (to[0], to[1]),
196                    4 => y0 = to[1],
197                    5 => x1 = to[0],
198                    6 => y1 = to[1],
199                    7 => x0 = to[0],
200                    _ => {
201                        x0 += d[0];
202                        x1 += d[0];
203                        y0 += d[1];
204                        y1 += d[1];
205                    }
206                }
207                Shape::Rect([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
208            }
209            Shape::Circle { center, radius } => match index {
210                1 => Shape::Circle {
211                    center: *center,
212                    radius: ((to[0] - center[0]).powi(2) + (to[1] - center[1]).powi(2)).sqrt(),
213                },
214                _ => Shape::Circle {
215                    center: shift(*center),
216                    radius: *radius,
217                },
218            },
219            Shape::Ellipse {
220                center,
221                radii,
222                rotation,
223            } => {
224                let v = [to[0] - center[0], to[1] - center[1]];
225                let (s, c) = rotation.sin_cos();
226                // The pointer in the ellipse's own axes.
227                let (x, y) = (v[0] * c + v[1] * s, -v[0] * s + v[1] * c);
228                let (mut radii, mut rotation, mut center) = (*radii, *rotation, *center);
229                match index {
230                    1 => radii[0] = x.abs().max(MIN_RADIUS),
231                    2 => radii[1] = y.abs().max(MIN_RADIUS),
232                    3 => rotation = v[0].atan2(-v[1]),
233                    _ => center = shift(center),
234                }
235                Shape::Ellipse {
236                    center,
237                    radii,
238                    rotation,
239                }
240            }
241            Shape::Path { points, closed } => {
242                let mut points = points.clone();
243                if let Some(p) = points.get_mut(index as usize) {
244                    *p = to;
245                } else {
246                    for p in &mut points {
247                        *p = shift(*p);
248                    }
249                }
250                Shape::Path {
251                    points,
252                    closed: *closed,
253                }
254            }
255        }
256    }
257}
258
259fn mid(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
260    [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]
261}
262
263/// How far out an ellipse's rotation handle is, past its second radius.
264const ROTATE_OUT: f64 = 1.3;
265
266/// The smallest radius a size handle gives an ellipse (image pixels).
267const MIN_RADIUS: f64 = 0.5;
268
269/// The point `(x, y)` of a frame centred at `center`, turned by
270/// `rotation` (image pixels).
271fn along(center: [f64; 2], rotation: f64, x: f64, y: f64) -> [f64; 2] {
272    let (s, c) = rotation.sin_cos();
273    [center[0] + x * c - y * s, center[1] + x * s + y * c]
274}
275
276/// The points of an ellipse's outline (image pixels).
277fn ellipse_points(center: [f64; 2], radii: [f64; 2], rotation: f64, n: usize) -> Vec<[f64; 2]> {
278    (0..n)
279        .map(|i| {
280            let a = std::f64::consts::TAU * i as f64 / n as f64;
281            along(center, rotation, radii[0] * a.cos(), radii[1] * a.sin())
282        })
283        .collect()
284}
285
286/// How an overlay stands out.
287#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
288pub enum Emphasis {
289    /// Drawn as usual.
290    #[default]
291    Normal,
292    /// The one being edited: a heavier line in the handle colour.
293    Selected,
294    /// In the background (a shape not being edited): half-transparent,
295    /// handles included.
296    Faint,
297}
298
299/// How an overlay is drawn.
300#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
301pub struct Style {
302    pub emphasis: Emphasis,
303    /// A dashed line (a shape that is not there yet, a feathered edge).
304    pub dashed: bool,
305}
306
307/// An overlay: a shape with an id, its handles, and whether it is a
308/// guide (drawn, never edited).
309#[derive(Clone, Debug, PartialEq)]
310pub struct Overlay {
311    pub id: String,
312    pub shape: Shape,
313    pub handles: Vec<Handle>,
314    pub label: Option<String>,
315    pub style: Style,
316}
317
318impl Overlay {
319    /// An editable overlay with the shape's standard handles.
320    pub fn new(id: impl Into<String>, shape: Shape) -> Overlay {
321        Overlay {
322            id: id.into(),
323            handles: shape.handles(),
324            shape,
325            label: None,
326            style: Style::default(),
327        }
328    }
329
330    /// A guide: drawn, no handles.
331    pub fn guide(id: impl Into<String>, shape: Shape) -> Overlay {
332        Overlay {
333            id: id.into(),
334            shape,
335            handles: Vec::new(),
336            label: None,
337            style: Style::default(),
338        }
339    }
340
341    /// With handles of its own instead of the shape's (a path with its
342    /// Bézier controls); the application applies their moves itself.
343    pub fn handles(mut self, handles: Vec<Handle>) -> Overlay {
344        self.handles = handles;
345        self
346    }
347
348    /// Drawn with this style.
349    pub fn style(mut self, style: Style) -> Overlay {
350        self.style = style;
351        self
352    }
353
354    /// The one being edited.
355    pub fn selected(mut self) -> Overlay {
356        self.style.emphasis = Emphasis::Selected;
357        self
358    }
359
360    /// In the background.
361    pub fn faint(mut self) -> Overlay {
362        self.style.emphasis = Emphasis::Faint;
363        self
364    }
365
366    /// With a dashed line.
367    pub fn dashed(mut self) -> Overlay {
368        self.style.dashed = true;
369        self
370    }
371
372    /// With a label drawn next to it.
373    pub fn label(mut self, label: impl Into<String>) -> Overlay {
374        self.label = Some(label.into());
375        self
376    }
377
378    /// Applies a handle signal for this overlay to its shape: `start` is
379    /// the shape when the gesture began (kept by the caller), so a
380    /// cancel puts it back. Returns whether the shape changed.
381    pub fn apply(&mut self, start: &Shape, signal: &crate::Signal) -> bool {
382        let crate::Signal::Handle {
383            overlay,
384            handle,
385            phase,
386            from,
387            at,
388            ..
389        } = signal
390        else {
391            return false;
392        };
393        if *overlay != self.id {
394            return false;
395        }
396        let shape = match phase {
397            crate::Phase::Cancel => start.clone(),
398            crate::Phase::Begin => return false,
399            _ => start.moved(*handle, *from, *at),
400        };
401        let changed = shape != self.shape;
402        self.handles = shape.handles();
403        self.shape = shape;
404        changed
405    }
406}
407
408/// How a handle is drawn.
409#[derive(Clone, Copy, Debug, PartialEq, Eq)]
410pub enum HandleState {
411    Rest,
412    Hover,
413    Active,
414}
415
416/// Draws one handle of the kit at `pos` (points).
417pub fn paint_handle(
418    painter: &Painter,
419    pos: Pos2,
420    kind: HandleKind,
421    state: HandleState,
422    t: &ViewportTokens,
423) {
424    paint_handle_styled(painter, pos, kind, state, Emphasis::Normal, t);
425}
426
427/// Draws one handle of the kit at `pos` (points), faint when its overlay
428/// is.
429pub fn paint_handle_styled(
430    painter: &Painter,
431    pos: Pos2,
432    kind: HandleKind,
433    state: HandleState,
434    emphasis: Emphasis,
435    t: &ViewportTokens,
436) {
437    let alpha = if emphasis == Emphasis::Faint {
438        FAINT
439    } else {
440        1.0
441    };
442    let fill = match state {
443        HandleState::Rest => t.handle,
444        HandleState::Hover | HandleState::Active => t.handle_hover,
445    }
446    .gamma_multiply(alpha);
447    let r = if state == HandleState::Rest {
448        DRAWN_RADIUS
449    } else {
450        DRAWN_RADIUS + 1.5
451    };
452    let w = |x: f32| snapped(painter, x);
453    let outline = Stroke::new(w(OUTLINE_WIDTH), t.handle_outline.gamma_multiply(alpha));
454    match kind {
455        HandleKind::Move => {
456            painter.circle(pos, r, fill, outline);
457            painter.circle_filled(pos, r * 0.35, outline.color);
458        }
459        HandleKind::Corner | HandleKind::Edge => {
460            let rect = egui::Rect::from_center_size(pos, vec2(r * 1.8, r * 1.8));
461            painter.rect(rect, 0.0, fill, outline, StrokeKind::Middle);
462        }
463        HandleKind::Rotate => {
464            painter.circle(pos, r, Color32::TRANSPARENT, Stroke::new(w(2.5), fill));
465            painter.circle_stroke(pos, r + 1.5, outline);
466        }
467        HandleKind::Feather => {
468            painter.circle(
469                pos,
470                r,
471                Color32::TRANSPARENT,
472                Stroke::new(w(LINE_WIDTH), fill),
473            );
474            painter.circle_stroke(pos, r * 0.5, Stroke::new(w(LINE_WIDTH), fill));
475        }
476        HandleKind::Control => {
477            // A small diamond: a tangent's end, not a point of the shape.
478            let d = r * 0.8;
479            let pts = vec![
480                pos + vec2(0.0, -d),
481                pos + vec2(d, 0.0),
482                pos + vec2(0.0, d),
483                pos + vec2(-d, 0.0),
484            ];
485            painter.add(egui::Shape::convex_polygon(pts, fill, outline));
486        }
487        HandleKind::Point | HandleKind::Size => {
488            painter.circle(pos, r, fill, outline);
489        }
490    }
491}
492
493/// How transparent a faint overlay is drawn.
494const FAINT: f32 = 0.45;
495
496/// A dash and the gap after it, in points, along a dashed line.
497const DASH: [f32; 2] = [6.0, 4.0];
498
499/// The points of a shape's outline on screen, and whether it closes;
500/// `None` for a point (drawn as a cross).
501fn outline(shape: &Shape, m: &Mapping) -> Option<(Vec<Pos2>, bool)> {
502    let s = |p: [f64; 2]| m.image_to_screen(p);
503    Some(match shape {
504        Shape::Point(_) => return None,
505        Shape::Line(a, b) => (vec![s(*a), s(*b)], false),
506        Shape::Rect(r) => (
507            vec![
508                s([r[0], r[1]]),
509                s([r[2], r[1]]),
510                s([r[2], r[3]]),
511                s([r[0], r[3]]),
512            ],
513            true,
514        ),
515        Shape::Circle { center, radius } => (
516            ellipse_points(*center, [*radius, *radius], 0.0, CURVE_POINTS)
517                .into_iter()
518                .map(s)
519                .collect(),
520            true,
521        ),
522        Shape::Ellipse {
523            center,
524            radii,
525            rotation,
526        } => (
527            ellipse_points(*center, *radii, *rotation, CURVE_POINTS)
528                .into_iter()
529                .map(s)
530                .collect(),
531            true,
532        ),
533        Shape::Path { points, closed } => (points.iter().map(|p| s(*p)).collect(), *closed),
534    })
535}
536
537/// How many points draw a circle or an ellipse.
538const CURVE_POINTS: usize = 96;
539
540/// Draws a polyline, plain or dashed.
541fn polyline(painter: &Painter, mut pts: Vec<Pos2>, closed: bool, stroke: Stroke, dashed: bool) {
542    if dashed {
543        if closed && let Some(first) = pts.first().copied() {
544            pts.push(first);
545        }
546        painter.extend(egui::Shape::dashed_line(&pts, stroke, DASH[0], DASH[1]));
547    } else if closed {
548        painter.add(egui::Shape::closed_line(pts, stroke));
549    } else {
550        painter.add(egui::Shape::line(pts, stroke));
551    }
552}
553
554/// Draws an overlay's shape (and its label) through a mapping, in its
555/// style.
556pub fn paint_shape(painter: &Painter, m: &Mapping, o: &Overlay, t: &ViewportTokens) {
557    let s = |p: [f64; 2]| m.image_to_screen(p);
558    let w = |x: f32| snapped(painter, x);
559    let (line_color, line_width, alpha) = match o.style.emphasis {
560        Emphasis::Normal => (t.guide, LINE_WIDTH, 1.0),
561        Emphasis::Selected => (t.handle, LINE_WIDTH + 0.5, 1.0),
562        Emphasis::Faint => (t.guide, LINE_WIDTH, FAINT),
563    };
564    let under = Stroke::new(
565        w(UNDER_WIDTH + line_width - LINE_WIDTH),
566        t.handle_outline.gamma_multiply(alpha),
567    );
568    let over = Stroke::new(w(line_width), line_color.gamma_multiply(alpha));
569    let dashed = o.style.dashed;
570    match outline(&o.shape, m) {
571        Some((pts, closed)) => {
572            for stroke in [under, over] {
573                polyline(painter, pts.clone(), closed, stroke, dashed);
574            }
575        }
576        None => {
577            let c = s(first_point(&o.shape));
578            for stroke in [under, over] {
579                for (a, b) in [
580                    (vec2(-6.0, 0.0), vec2(6.0, 0.0)),
581                    (vec2(0.0, -6.0), vec2(0.0, 6.0)),
582                ] {
583                    polyline(painter, vec![c + a, c + b], false, stroke, false);
584                }
585            }
586        }
587    }
588    if let Some(label) = &o.label {
589        let at = o
590            .handles
591            .first()
592            .map_or_else(|| first_point(&o.shape), |h| h.at);
593        let mut painter = painter.clone();
594        painter.multiply_opacity(alpha);
595        paint_label(
596            &painter,
597            s(at) + vec2(8.0, -8.0),
598            egui::Align2::LEFT_BOTTOM,
599            label,
600        );
601    }
602}
603
604/// Draws `text` as a label over an image, through the kit's
605/// `viewport-label` component: a translucent pill (its `fill`, `radius`,
606/// `padding-x` and `padding-y`) holding the text in its `text` colour, at
607/// its `font-size` (the `Small` text style's when the kit gives none).
608/// `anchor` says which point of the label sits at `at` (points):
609/// `LEFT_BOTTOM` puts it above and right of `at`. An overlay's label
610/// ([`Overlay::label`]) is drawn this way; so is a HUD's readout over an
611/// image. Returns the rectangle the label covers.
612pub fn paint_label(
613    painter: &Painter,
614    at: Pos2,
615    anchor: egui::Align2,
616    text: impl Into<String>,
617) -> egui::Rect {
618    let ctx = painter.ctx();
619    let kit = egui_pop_core::kit::Kit::of(ctx);
620    let c = &kit.viewport_label;
621    let size = if c.data.font_size > 0.0 {
622        c.data.font_size
623    } else {
624        egui_pop_core::theme::Tokens::of(ctx).font.small
625    };
626    let galley = painter.layout_no_wrap(
627        text.into(),
628        egui::FontId::proportional(size),
629        Color32::PLACEHOLDER,
630    );
631    let rect = anchor.anchor_size(at, c.measure(galley.size()));
632    c.paint_part(
633        &egui_pop_core::kit::KitCx {
634            painter,
635            ppp: ctx.pixels_per_point(),
636        },
637        &egui_pop_core::kit::Part {
638            rect,
639            room: rect,
640            state: egui_pop_core::kit::State::REST,
641            label: Some(&galley),
642        },
643    );
644    rect
645}
646
647fn first_point(shape: &Shape) -> [f64; 2] {
648    match shape {
649        Shape::Point(p) | Shape::Line(p, _) => *p,
650        Shape::Rect(r) => [r[0], r[1]],
651        Shape::Circle { center, .. } | Shape::Ellipse { center, .. } => *center,
652        Shape::Path { points, .. } => points.first().copied().unwrap_or([0.0, 0.0]),
653    }
654}
655
656/// How close to an outline a click lands on it, in points.
657pub const EDGE_RADIUS: f32 = 6.0;
658
659/// The outline under `pos` (points), topmost overlay first, guides left
660/// out: the overlay's index, the segment (between points `i` and `i + 1`
661/// of a path or a line, the box's top, right, bottom and left edges `0`
662/// to `3`, `0` for a circle or an ellipse) and the nearest point of it
663/// in image pixels.
664pub fn hit_edge(overlays: &[Overlay], m: &Mapping, pos: Pos2) -> Option<(usize, u32, [f64; 2])> {
665    for (i, o) in overlays.iter().enumerate().rev() {
666        if o.handles.is_empty() {
667            continue;
668        }
669        let Some((pts, closed)) = outline(&o.shape, m) else {
670            continue;
671        };
672        let curve = matches!(o.shape, Shape::Circle { .. } | Shape::Ellipse { .. });
673        let n = pts.len();
674        let count = if closed { n } else { n.saturating_sub(1) };
675        let mut best: Option<(u32, Pos2, f32)> = None;
676        for k in 0..count {
677            let (a, b) = (pts[k], pts[(k + 1) % n]);
678            let ab = b - a;
679            let t = if ab.length_sq() > 0.0 {
680                ((pos - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0)
681            } else {
682                0.0
683            };
684            let near = a + ab * t;
685            let d = near.distance(pos);
686            if d <= EDGE_RADIUS && best.is_none_or(|b| d < b.2) {
687                let segment = if curve { 0 } else { k as u32 };
688                best = Some((segment, near, d));
689            }
690        }
691        if let Some((segment, near, _)) = best {
692            return Some((i, segment, m.screen_to_image(near)));
693        }
694    }
695    None
696}
697
698/// The handle under `pos` (points), topmost overlay first.
699pub fn hit(overlays: &[Overlay], m: &Mapping, pos: Pos2) -> Option<(usize, Handle)> {
700    let mut best: Option<(usize, Handle, f32)> = None;
701    for (i, o) in overlays.iter().enumerate().rev() {
702        for h in &o.handles {
703            let d = m.image_to_screen(h.at).distance(pos);
704            if d <= HIT_RADIUS && best.as_ref().is_none_or(|b| d < b.2) {
705                best = Some((i, *h, d));
706            }
707        }
708        if best.is_some() {
709            break;
710        }
711    }
712    best.map(|(i, h, _)| (i, h))
713}
714
715#[cfg(test)]
716mod tests {
717    use super::*;
718
719    #[test]
720    fn a_box_follows_its_corner_edge_and_body() {
721        let r = Shape::Rect([10.0, 10.0, 50.0, 30.0]);
722        assert_eq!(
723            r.moved(2, [50.0, 30.0], [60.0, 40.0]),
724            Shape::Rect([10.0, 10.0, 60.0, 40.0])
725        );
726        assert_eq!(
727            r.moved(7, [10.0, 20.0], [5.0, 99.0]),
728            Shape::Rect([5.0, 10.0, 50.0, 30.0])
729        );
730        assert_eq!(
731            r.moved(8, [30.0, 20.0], [31.0, 22.0]),
732            Shape::Rect([11.0, 12.0, 51.0, 32.0])
733        );
734        // Dragged past the opposite corner: still a box.
735        assert_eq!(
736            r.moved(0, [10.0, 10.0], [70.0, 50.0]),
737            Shape::Rect([50.0, 30.0, 70.0, 50.0])
738        );
739    }
740
741    #[test]
742    fn an_ellipse_sizes_along_its_axes_and_turns() {
743        let e = Shape::Ellipse {
744            center: [0.0, 0.0],
745            radii: [10.0, 5.0],
746            rotation: 0.0,
747        };
748        let h = e.handles();
749        assert_eq!(h.len(), 4);
750        assert_eq!(h[1].at, [10.0, 0.0]);
751        assert_eq!(h[3].kind, HandleKind::Rotate);
752        // The first radius follows the pointer along its own axis only.
753        assert_eq!(
754            e.moved(1, [10.0, 0.0], [20.0, 7.0]),
755            Shape::Ellipse {
756                center: [0.0, 0.0],
757                radii: [20.0, 5.0],
758                rotation: 0.0
759            }
760        );
761        // The rotation handle, dragged to the right: a quarter turn.
762        let Shape::Ellipse { rotation, .. } = e.moved(3, h[3].at, [8.0, 0.0]) else {
763            panic!()
764        };
765        assert!((rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9);
766        let turned = Shape::Ellipse {
767            center: [0.0, 0.0],
768            radii: [10.0, 5.0],
769            rotation,
770        };
771        let h = turned.handles();
772        assert!((h[1].at[0]).abs() < 1e-9 && (h[1].at[1] - 10.0).abs() < 1e-9);
773    }
774
775    #[test]
776    fn a_circle_sizes_from_its_size_handle() {
777        let c = Shape::Circle {
778            center: [0.0, 0.0],
779            radius: 5.0,
780        };
781        assert_eq!(
782            c.moved(1, [5.0, 0.0], [0.0, 12.0]),
783            Shape::Circle {
784                center: [0.0, 0.0],
785                radius: 12.0
786            }
787        );
788    }
789}