Skip to main content

egui_pop_core/
placement.rs

1//! Placement of a floating element (popover, menu, tooltip) next to an
2//! anchor, inside bounds: on the preferred side if it fits, else flipped
3//! to the opposite side, else on the side with more room; then shifted
4//! along the side to stay inside, and shrunk only when larger than the
5//! bounds.
6//!
7//! egui's own `RectAlign::find_best_align` flips among candidate
8//! alignments but neither shifts nor shrinks; this is the small part of
9//! floating-ui's model egui-pop needs, pure geometry, tested by
10//! properties.
11//!
12//! ```
13//! use egui::{Rect, pos2, vec2};
14//! use egui_pop_core::placement::{Align, Placement, Side, place};
15//!
16//! let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
17//! // A button near the bottom: a menu asked below it opens above.
18//! let anchor = Rect::from_min_size(pos2(20.0, 270.0), vec2(80.0, 24.0));
19//! let p = place(&Placement::new(anchor, vec2(160.0, 120.0), bounds).side(Side::Bottom));
20//! assert_eq!(p.side, Side::Top);
21//! assert!(p.flipped);
22//! assert!(bounds.contains_rect(p.rect));
23//! ```
24
25use egui::{Rect, Vec2, pos2, vec2};
26use serde::Serialize;
27
28/// Which side of the anchor. Start and end are left and right in a
29/// left-to-right layout.
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
31pub enum Side {
32    Top,
33    Bottom,
34    Start,
35    End,
36}
37
38impl Side {
39    pub fn opposite(self) -> Side {
40        match self {
41            Side::Top => Side::Bottom,
42            Side::Bottom => Side::Top,
43            Side::Start => Side::End,
44            Side::End => Side::Start,
45        }
46    }
47
48    fn vertical(self) -> bool {
49        matches!(self, Side::Top | Side::Bottom)
50    }
51}
52
53/// How the element lines up with the anchor along the side.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
55pub enum Align {
56    Start,
57    Center,
58    End,
59}
60
61/// What to place, where.
62#[derive(Clone, Copy, Debug, PartialEq)]
63pub struct Placement {
64    pub anchor: Rect,
65    pub size: Vec2,
66    pub bounds: Rect,
67    pub side: Side,
68    pub align: Align,
69    /// Space between the anchor and the element.
70    pub gap: f32,
71}
72
73impl Placement {
74    pub fn new(anchor: Rect, size: Vec2, bounds: Rect) -> Self {
75        Self {
76            anchor,
77            size,
78            bounds,
79            side: Side::Bottom,
80            align: Align::Start,
81            gap: 4.0,
82        }
83    }
84
85    pub fn side(mut self, side: Side) -> Self {
86        self.side = side;
87        self
88    }
89
90    pub fn align(mut self, align: Align) -> Self {
91        self.align = align;
92        self
93    }
94
95    pub fn gap(mut self, gap: f32) -> Self {
96        self.gap = gap;
97        self
98    }
99}
100
101/// Where it went.
102#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
103pub struct Placed {
104    #[serde(skip)]
105    pub rect: Rect,
106    /// The side used.
107    pub side: Side,
108    /// Not the preferred side.
109    pub flipped: bool,
110    /// Moved along the side to stay inside the bounds, in points.
111    pub shift: f32,
112    /// Smaller than asked: it did not fit the bounds.
113    pub shrunk: bool,
114}
115
116/// Room for the element on a side of the anchor, within the bounds.
117fn room(p: &Placement, side: Side) -> f32 {
118    let (a, b) = (p.anchor, p.bounds);
119    match side {
120        Side::Top => a.top() - b.top() - p.gap,
121        Side::Bottom => b.bottom() - a.bottom() - p.gap,
122        Side::Start => a.left() - b.left() - p.gap,
123        Side::End => b.right() - a.right() - p.gap,
124    }
125}
126
127/// Places the element.
128pub fn place(p: &Placement) -> Placed {
129    let need = |side: Side| if side.vertical() { p.size.y } else { p.size.x };
130    let fits = |side: Side| room(p, side) >= need(side);
131    let opposite = p.side.opposite();
132    // The opposite side when the preferred one is too small and the
133    // opposite fits, or at least has more room.
134    let flip = !fits(p.side) && (fits(opposite) || room(p, opposite) > room(p, p.side));
135    let (side, flipped) = if flip {
136        (opposite, true)
137    } else {
138        (p.side, false)
139    };
140    let mut size = p.size;
141    let mut shrunk = false;
142    // Never larger than the bounds, nor than the room on the side.
143    let main_room = room(p, side).max(0.0);
144    if side.vertical() {
145        if size.y > main_room {
146            size.y = main_room;
147            shrunk = true;
148        }
149        if size.x > p.bounds.width() {
150            size.x = p.bounds.width();
151            shrunk = true;
152        }
153    } else {
154        if size.x > main_room {
155            size.x = main_room;
156            shrunk = true;
157        }
158        if size.y > p.bounds.height() {
159            size.y = p.bounds.height();
160            shrunk = true;
161        }
162    }
163    let a = p.anchor;
164    let cross = |start: f32, end: f32, len: f32| match p.align {
165        Align::Start => start,
166        Align::Center => (start + end - len) / 2.0,
167        Align::End => end - len,
168    };
169    let min = match side {
170        Side::Top => pos2(cross(a.left(), a.right(), size.x), a.top() - p.gap - size.y),
171        Side::Bottom => pos2(cross(a.left(), a.right(), size.x), a.bottom() + p.gap),
172        Side::Start => pos2(
173            a.left() - p.gap - size.x,
174            cross(a.top(), a.bottom(), size.y),
175        ),
176        Side::End => pos2(a.right() + p.gap, cross(a.top(), a.bottom(), size.y)),
177    };
178    let mut rect = Rect::from_min_size(min, size);
179    // Shift along the side to stay inside.
180    let b = p.bounds;
181    let mut delta = vec2(0.0, 0.0);
182    if side.vertical() {
183        if rect.left() < b.left() {
184            delta.x = b.left() - rect.left();
185        } else if rect.right() > b.right() {
186            delta.x = b.right() - rect.right();
187        }
188    } else if rect.top() < b.top() {
189        delta.y = b.top() - rect.top();
190    } else if rect.bottom() > b.bottom() {
191        delta.y = b.bottom() - rect.bottom();
192    }
193    rect = rect.translate(delta);
194    // Last resort when the room was negative: inside the bounds anyway.
195    if !b.contains_rect(rect) {
196        let min = pos2(
197            rect.left()
198                .clamp(b.left(), (b.right() - rect.width()).max(b.left())),
199            rect.top()
200                .clamp(b.top(), (b.bottom() - rect.height()).max(b.top())),
201        );
202        rect = Rect::from_min_size(min, rect.size().min(b.size()));
203    }
204    Placed {
205        rect,
206        side,
207        flipped,
208        shift: delta.x + delta.y,
209        shrunk,
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    /// A small deterministic generator, so the properties run the same
218    /// cases everywhere.
219    struct Rng(u64);
220
221    impl Rng {
222        fn next(&mut self) -> f32 {
223            self.0 ^= self.0 << 13;
224            self.0 ^= self.0 >> 7;
225            self.0 ^= self.0 << 17;
226            (self.0 % 10_000) as f32 / 10_000.0
227        }
228    }
229
230    const SIDES: [Side; 4] = [Side::Top, Side::Bottom, Side::Start, Side::End];
231    const ALIGNS: [Align; 3] = [Align::Start, Align::Center, Align::End];
232
233    #[test]
234    fn placement_properties_hold_over_many_cases() {
235        let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
236        let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(800.0, 600.0));
237        for case in 0..5_000 {
238            let anchor = Rect::from_min_size(
239                pos2(rng.next() * 780.0, rng.next() * 580.0),
240                vec2(4.0 + rng.next() * 120.0, 4.0 + rng.next() * 40.0),
241            )
242            .intersect(bounds);
243            let size = vec2(10.0 + rng.next() * 500.0, 10.0 + rng.next() * 400.0);
244            let side = SIDES[case % 4];
245            let align = ALIGNS[case % 3];
246            let p = Placement::new(anchor, size, bounds).side(side).align(align);
247            let r = place(&p);
248            let ctx = format!("case {case}: {p:?} -> {r:?} {:?}", r.rect);
249            // Always inside the bounds.
250            let eps = 0.01;
251            assert!(bounds.expand(eps).contains_rect(r.rect), "{ctx}");
252            // Never larger than asked.
253            assert!(
254                r.rect.width() <= size.x + eps && r.rect.height() <= size.y + eps,
255                "{ctx}"
256            );
257            // Where it fits on the preferred side, it goes there, unshrunk,
258            // without covering the anchor.
259            if room(&p, side) >= if side.vertical() { size.y } else { size.x }
260                && size.x <= bounds.width()
261                && size.y <= bounds.height()
262            {
263                assert_eq!(r.side, side, "{ctx}");
264                assert!(!r.flipped && !r.shrunk, "{ctx}");
265            }
266            // Whenever it is not shrunk, it does not cover the anchor.
267            if !r.shrunk {
268                assert!(!r.rect.shrink(eps).intersects(anchor.shrink(eps)), "{ctx}");
269            }
270        }
271    }
272
273    #[test]
274    fn it_shifts_along_the_side_to_stay_inside() {
275        let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
276        let anchor = Rect::from_min_size(pos2(360.0, 20.0), vec2(30.0, 20.0));
277        let r = place(&Placement::new(anchor, vec2(120.0, 80.0), bounds));
278        assert_eq!(r.side, Side::Bottom);
279        assert_eq!(r.rect.right(), 400.0);
280        assert_eq!(r.shift, -80.0);
281        assert!(!r.flipped && !r.shrunk);
282    }
283
284    #[test]
285    fn it_shrinks_only_when_no_side_has_room() {
286        let bounds = Rect::from_min_size(pos2(0.0, 0.0), vec2(400.0, 300.0));
287        let anchor = Rect::from_min_size(pos2(10.0, 140.0), vec2(30.0, 20.0));
288        let r = place(&Placement::new(anchor, vec2(100.0, 200.0), bounds));
289        // 136 points above, 136 below: the bottom keeps it, shrunk.
290        assert_eq!(r.side, Side::Bottom);
291        assert!(r.shrunk);
292        assert!(bounds.contains_rect(r.rect));
293    }
294}