Skip to main content

nativeview_layout/
overlay.rs

1//! Zero-allocation pure-Rust anchored overlay collision-flipping, viewport clamping,
2//! auto-sizing, arrow center tracking, and submenu safe-polygon hover corridor solver.
3//!
4//! Shared across `nativeview-layout` (Skia / native top-layer reconciliation), `nativeview-backend-web`
5//! (CSS Anchor Positioning fallback), and `nativeview-ui` (`nativeview_ui::positioning`).
6
7pub use nativeview_tables::tables::{Alignment, OverlayPlacement as Placement, Side};
8
9const EPS: f32 = 1e-4;
10
11/// 2D point in logical viewport coordinates.
12#[derive(Debug, Clone, Copy, PartialEq, Default)]
13pub struct Point {
14    pub x: f32,
15    pub y: f32,
16}
17
18impl Point {
19    #[inline]
20    pub const fn new(x: f32, y: f32) -> Self {
21        Self { x, y }
22    }
23
24    #[inline]
25    pub fn is_finite(self) -> bool {
26        self.x.is_finite() && self.y.is_finite()
27    }
28}
29
30/// Axis-aligned rectangle in logical viewport coordinates.
31#[derive(Debug, Clone, Copy, PartialEq, Default)]
32pub struct Rect {
33    pub x: f32,
34    pub y: f32,
35    pub width: f32,
36    pub height: f32,
37}
38
39impl Rect {
40    #[inline]
41    pub const fn new(x: f32, y: f32, width: f32, height: f32) -> Self {
42        Self {
43            x,
44            y,
45            width,
46            height,
47        }
48    }
49
50    #[inline]
51    pub fn right(self) -> f32 {
52        self.x + self.width
53    }
54
55    #[inline]
56    pub fn bottom(self) -> f32 {
57        self.y + self.height
58    }
59
60    #[inline]
61    pub fn center_x(self) -> f32 {
62        self.x + self.width * 0.5
63    }
64
65    #[inline]
66    pub fn center_y(self) -> f32 {
67        self.y + self.height * 0.5
68    }
69
70    #[inline]
71    pub fn is_valid(self) -> bool {
72        self.x.is_finite()
73            && self.y.is_finite()
74            && self.width.is_finite()
75            && self.height.is_finite()
76            && self.width >= 0.0
77            && self.height >= 0.0
78    }
79
80    #[inline]
81    pub fn contains_point(self, p: Point) -> bool {
82        self.is_valid()
83            && p.is_finite()
84            && p.x >= self.x
85            && p.x <= self.right()
86            && p.y >= self.y
87            && p.y <= self.bottom()
88    }
89}
90
91/// Logical dimensions of an overlay panel.
92#[derive(Debug, Clone, Copy, PartialEq, Default)]
93pub struct Size {
94    pub width: f32,
95    pub height: f32,
96}
97
98impl Size {
99    #[inline]
100    pub const fn new(width: f32, height: f32) -> Self {
101        Self { width, height }
102    }
103}
104
105/// Logical viewport dimensions (`[0, width] × [0, height]`).
106#[derive(Debug, Clone, Copy, PartialEq, Default)]
107pub struct Viewport {
108    pub width: f32,
109    pub height: f32,
110}
111
112impl Viewport {
113    #[inline]
114    pub const fn new(width: f32, height: f32) -> Self {
115        Self { width, height }
116    }
117}
118
119/// Configuration for [`compute_overlay_position`].
120#[derive(Debug, Clone, PartialEq)]
121pub struct PositionOptions {
122    pub placement: Placement,
123    pub offset: f32,
124    pub viewport_padding: f32,
125    pub flip: bool,
126    pub shift: bool,
127    pub auto_size: bool,
128    pub fallback_placements: Vec<Placement>,
129}
130
131impl Default for PositionOptions {
132    fn default() -> Self {
133        Self {
134            placement: Placement::Bottom,
135            offset: 8.0,
136            viewport_padding: 8.0,
137            flip: true,
138            shift: true,
139            auto_size: false,
140            fallback_placements: Vec::new(),
141        }
142    }
143}
144
145impl PositionOptions {
146    pub fn new(placement: Placement) -> Self {
147        Self {
148            placement,
149            ..Self::default()
150        }
151    }
152
153    pub fn with_offset(mut self, offset: f32) -> Self {
154        self.offset = offset;
155        self
156    }
157
158    pub fn with_viewport_padding(mut self, padding: f32) -> Self {
159        self.viewport_padding = padding;
160        self
161    }
162
163    pub fn with_flip(mut self, flip: bool) -> Self {
164        self.flip = flip;
165        self
166    }
167
168    pub fn with_shift(mut self, shift: bool) -> Self {
169        self.shift = shift;
170        self
171    }
172
173    pub fn with_auto_size(mut self, auto_size: bool) -> Self {
174        self.auto_size = auto_size;
175        self
176    }
177
178    pub fn with_fallbacks(mut self, fallbacks: Vec<Placement>) -> Self {
179        self.fallback_placements = fallbacks;
180        self
181    }
182}
183
184/// Resolved overlay coordinates, placement, arrow offset, and size constraints.
185#[derive(Debug, Clone, Copy, PartialEq)]
186pub struct ComputedPosition {
187    pub x: f32,
188    pub y: f32,
189    pub placement: Placement,
190    pub arrow_x: Option<f32>,
191    pub arrow_y: Option<f32>,
192    pub max_width: Option<f32>,
193    pub max_height: Option<f32>,
194    pub flipped: bool,
195    pub shifted: bool,
196}
197
198#[inline]
199fn sanitize_non_neg(v: f32) -> f32 {
200    if v.is_finite() { v.max(0.0) } else { 0.0 }
201}
202
203#[inline]
204fn sanitize_finite(v: f32) -> f32 {
205    if v.is_finite() { v } else { 0.0 }
206}
207
208#[inline]
209fn push_unique_arr<const N: usize>(buf: &mut [Placement; N], len: &mut usize, p: Placement) {
210    if *len < N && !buf[..*len].contains(&p) {
211        buf[*len] = p;
212        *len += 1;
213    }
214}
215
216#[derive(Clone, Copy)]
217struct SolverCtx {
218    anchor: Rect,
219    overlay: Size,
220    offset: f32,
221    vp_w: f32,
222    vp_h: f32,
223    pad_x: f32,
224    pad_y: f32,
225}
226
227impl SolverCtx {
228    fn raw_coords(self, size: Size, placement: Placement) -> (f32, f32) {
229        let x = match placement.side() {
230            Side::Left => self.anchor.x - self.offset - size.width,
231            Side::Right => self.anchor.right() + self.offset,
232            Side::Top | Side::Bottom => match placement.alignment() {
233                Alignment::Start => self.anchor.x,
234                Alignment::Center => self.anchor.x + (self.anchor.width - size.width) * 0.5,
235                Alignment::End => self.anchor.right() - size.width,
236            },
237        };
238        let y = match placement.side() {
239            Side::Top => self.anchor.y - self.offset - size.height,
240            Side::Bottom => self.anchor.bottom() + self.offset,
241            Side::Left | Side::Right => match placement.alignment() {
242                Alignment::Start => self.anchor.y,
243                Alignment::Center => self.anchor.y + (self.anchor.height - size.height) * 0.5,
244                Alignment::End => self.anchor.bottom() - size.height,
245            },
246        };
247        (x, y)
248    }
249
250    fn available_main_space(self, side: Side) -> f32 {
251        let usable_w = (self.vp_w - 2.0 * self.pad_x).max(0.0);
252        let usable_h = (self.vp_h - 2.0 * self.pad_y).max(0.0);
253        match side {
254            Side::Top => (self.anchor.y - self.offset - self.pad_y).clamp(0.0, usable_h),
255            Side::Bottom => ((self.vp_h - self.pad_y) - (self.anchor.bottom() + self.offset))
256                .clamp(0.0, usable_h),
257            Side::Left => (self.anchor.x - self.offset - self.pad_x).clamp(0.0, usable_w),
258            Side::Right => ((self.vp_w - self.pad_x) - (self.anchor.right() + self.offset))
259                .clamp(0.0, usable_w),
260        }
261    }
262
263    fn overflows(self, placement: Placement) -> (f32, f32) {
264        let (x, y) = self.raw_coords(self.overlay, placement);
265        let left_ov = (self.pad_x - x).max(0.0);
266        let right_ov = ((x + self.overlay.width) - (self.vp_w - self.pad_x)).max(0.0);
267        let top_ov = (self.pad_y - y).max(0.0);
268        let bottom_ov = ((y + self.overlay.height) - (self.vp_h - self.pad_y)).max(0.0);
269        let main_ov = if placement.side().is_vertical() {
270            top_ov + bottom_ov
271        } else {
272            left_ov + right_ov
273        };
274        let cross_ov = if placement.side().is_vertical() {
275            left_ov + right_ov
276        } else {
277            top_ov + bottom_ov
278        };
279        (main_ov, cross_ov)
280    }
281
282    fn select_placement(self, primary: &[Placement], cross: &[Placement], shift: bool) -> Placement {
283        // 1. Exact fit in primary tier (normal fit, single-axis flip, or corner double-flip).
284        for &c in primary {
285            let (m, x) = self.overflows(c);
286            if m <= EPS && x <= EPS {
287                return c;
288            }
289        }
290        // 2. Main-axis fit in primary tier when cross-axis shifting is enabled.
291        if shift {
292            for &c in primary {
293                if self.overflows(c).0 <= EPS {
294                    return c;
295                }
296            }
297        }
298        // 3. Cross-axis tier: exact fit, then main-axis fit when shifting is enabled.
299        for &c in cross {
300            let (m, x) = self.overflows(c);
301            if m <= EPS && x <= EPS {
302                return c;
303            }
304        }
305        if shift {
306            for &c in cross {
307                if self.overflows(c).0 <= EPS {
308                    return c;
309                }
310            }
311        }
312        // 4. Tiny viewport fallback: pick candidate with maximum available main-axis space.
313        let mut best = primary[0];
314        let mut best_space = self.available_main_space(best.side());
315        let mut best_cross = self.overflows(best).1;
316        for &c in primary.iter().chain(cross.iter()).skip(1) {
317            let space = self.available_main_space(c.side());
318            let cross_ov = self.overflows(c).1;
319            if space > best_space + EPS
320                || ((space - best_space).abs() <= EPS && cross_ov + EPS < best_cross)
321            {
322                best = c;
323                best_space = space;
324                best_cross = cross_ov;
325            }
326        }
327        best
328    }
329
330    /// Zero-allocation candidate selection using fixed stack arrays (`[Placement; 12]`).
331    fn pick_placement(self, options: &PositionOptions) -> Placement {
332        let req = options.placement;
333        if !options.flip {
334            return req;
335        }
336        if !options.fallback_placements.is_empty() {
337            let mut candidates = [req; 12];
338            let mut len = 0usize;
339            push_unique_arr(&mut candidates, &mut len, req);
340            for &fb in &options.fallback_placements {
341                push_unique_arr(&mut candidates, &mut len, fb);
342            }
343            return self.select_placement(&candidates[..len], &[], options.shift);
344        }
345        let mut primary = [req; 12];
346        let mut primary_len = 0usize;
347        push_unique_arr(&mut primary, &mut primary_len, req);
348        push_unique_arr(&mut primary, &mut primary_len, req.opposite());
349        push_unique_arr(&mut primary, &mut primary_len, req.flip_alignment());
350        push_unique_arr(&mut primary, &mut primary_len, req.opposite().flip_alignment());
351
352        let cross_sides = if req.side().is_vertical() {
353            [Side::Right, Side::Left]
354        } else {
355            [Side::Bottom, Side::Top]
356        };
357        let mut cross = [req; 12];
358        let mut cross_len = 0usize;
359        for side in cross_sides {
360            push_unique_arr(
361                &mut cross,
362                &mut cross_len,
363                Placement::from_side_align(side, req.alignment()),
364            );
365            push_unique_arr(
366                &mut cross,
367                &mut cross_len,
368                Placement::from_side_align(side, req.alignment().opposite()),
369            );
370        }
371        self.select_placement(&primary[..primary_len], &cross[..cross_len], options.shift)
372    }
373}
374
375/// Computes the collision-flipped, viewport-clamped, optionally auto-sized position and arrow
376/// offset for an overlay anchored to `anchor` within `viewport` with **0 heap allocations**.
377pub fn compute_overlay_position(
378    anchor: Rect,
379    overlay: Size,
380    viewport: Viewport,
381    options: &PositionOptions,
382) -> ComputedPosition {
383    let vp_w = sanitize_non_neg(viewport.width);
384    let vp_h = sanitize_non_neg(viewport.height);
385    let raw_pad = sanitize_non_neg(options.viewport_padding);
386    let ctx = SolverCtx {
387        anchor: Rect::new(
388            sanitize_finite(anchor.x),
389            sanitize_finite(anchor.y),
390            sanitize_non_neg(anchor.width),
391            sanitize_non_neg(anchor.height),
392        ),
393        overlay: Size::new(
394            sanitize_non_neg(overlay.width),
395            sanitize_non_neg(overlay.height),
396        ),
397        offset: sanitize_finite(options.offset),
398        vp_w,
399        vp_h,
400        pad_x: raw_pad.min(vp_w * 0.5),
401        pad_y: raw_pad.min(vp_h * 0.5),
402    };
403
404    let chosen = ctx.pick_placement(options);
405    let flipped = chosen != options.placement;
406
407    let (max_width, max_height, eff_size) = if options.auto_size {
408        let avail_main = ctx.available_main_space(chosen.side());
409        let avail_w = if chosen.side().is_vertical() {
410            (ctx.vp_w - 2.0 * ctx.pad_x).max(0.0)
411        } else {
412            avail_main
413        };
414        let avail_h = if chosen.side().is_vertical() {
415            avail_main
416        } else {
417            (ctx.vp_h - 2.0 * ctx.pad_y).max(0.0)
418        };
419        (
420            Some(avail_w),
421            Some(avail_h),
422            Size::new(ctx.overlay.width.min(avail_w), ctx.overlay.height.min(avail_h)),
423        )
424    } else {
425        (None, None, ctx.overlay)
426    };
427
428    let (mut x, mut y) = ctx.raw_coords(eff_size, chosen);
429    let mut shifted = false;
430
431    if options.shift {
432        let max_x = (ctx.vp_w - ctx.pad_x - eff_size.width).max(ctx.pad_x);
433        let clamped_x = x.clamp(ctx.pad_x, max_x);
434        if (clamped_x - x).abs() > EPS {
435            x = clamped_x;
436            shifted = true;
437        }
438        let max_y = (ctx.vp_h - ctx.pad_y - eff_size.height).max(ctx.pad_y);
439        let clamped_y = y.clamp(ctx.pad_y, max_y);
440        if (clamped_y - y).abs() > EPS {
441            y = clamped_y;
442            shifted = true;
443        }
444    }
445
446    let (arrow_x, arrow_y) = if chosen.side().is_vertical() {
447        (Some((ctx.anchor.center_x() - x).clamp(0.0, eff_size.width)), None)
448    } else {
449        (None, Some((ctx.anchor.center_y() - y).clamp(0.0, eff_size.height)))
450    };
451
452    ComputedPosition {
453        x,
454        y,
455        placement: chosen,
456        arrow_x,
457        arrow_y,
458        max_width,
459        max_height,
460        flipped,
461        shifted,
462    }
463}
464
465#[inline]
466fn cross_2d(a: Point, b: Point, p: Point) -> f32 {
467    (b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)
468}
469
470#[inline]
471fn point_in_triangle(p: Point, a: Point, b: Point, c: Point) -> bool {
472    let (d1, d2, d3) = (cross_2d(a, b, p), cross_2d(b, c, p), cross_2d(c, a, p));
473    !((d1 < -EPS || d2 < -EPS || d3 < -EPS) && (d1 > EPS || d2 > EPS || d3 > EPS))
474}
475
476/// Safe-triangle hover corridor test for cascading submenus.
477pub fn point_in_safe_polygon(cursor: Point, prev_cursor: Point, submenu_rect: Rect) -> bool {
478    if !submenu_rect.is_valid() || !cursor.is_finite() || !prev_cursor.is_finite() {
479        return false;
480    }
481    if submenu_rect.contains_point(cursor) {
482        return true;
483    }
484    if submenu_rect.contains_point(prev_cursor) {
485        return false;
486    }
487
488    let tl = Point::new(submenu_rect.x, submenu_rect.y);
489    let tr = Point::new(submenu_rect.right(), submenu_rect.y);
490    let br = Point::new(submenu_rect.right(), submenu_rect.bottom());
491    let bl = Point::new(submenu_rect.x, submenu_rect.bottom());
492
493    let (c1, c2) = if prev_cursor.x < submenu_rect.x {
494        if prev_cursor.y < submenu_rect.y {
495            (tr, bl)
496        } else if prev_cursor.y > submenu_rect.bottom() {
497            (tl, br)
498        } else {
499            (tl, bl)
500        }
501    } else if prev_cursor.x > submenu_rect.right() {
502        if prev_cursor.y < submenu_rect.y {
503            (tl, br)
504        } else if prev_cursor.y > submenu_rect.bottom() {
505            (tr, bl)
506        } else {
507            (tr, br)
508        }
509    } else if prev_cursor.y < submenu_rect.y {
510        (tl, tr)
511    } else {
512        (bl, br)
513    };
514
515    point_in_triangle(cursor, prev_cursor, c1, c2)
516}