Skip to main content

iced_cube/overlay/
tooltip.rs

1//! A small label shown while the pointer rests on an element, or while
2//! something inside the element has keyboard focus.
3//!
4//! A finger shows it while held. Once the finger lifts, the bubble stays
5//! closed until a mouse is used, so a tap on a phone does not leave it open.
6//!
7//! iced has no general focus model, so the tooltip follows the widgets that
8//! report focus to operations: text fields, text editors and the focusable
9//! parts of this library. Focus that arrives with a pointer press, such as
10//! clicking into a field, does not show the bubble.
11
12use iced::advanced::layout::{self, Layout};
13use iced::advanced::widget::operation::Focusable;
14use iced::advanced::widget::{Operation, Tree, Widget, tree};
15use iced::advanced::{Clipboard, Shell, overlay, renderer};
16use iced::time::{Duration, Instant};
17use iced::widget::{self, container, text};
18use iced::{
19    Background, Border, Element, Event, Length, Padding, Point, Rectangle, Renderer, Size, Theme,
20    Vector, mouse, touch, window,
21};
22
23use crate::after_touch::after_touch;
24use crate::theme::{Tokens, radius, space, text_size};
25
26/// Where the bubble appears relative to its element.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
28pub enum Position {
29    #[default]
30    Top,
31    Bottom,
32    Left,
33    Right,
34    /// Follows the pointer. A bubble shown for keyboard focus sits on top.
35    FollowCursor,
36}
37
38impl Position {
39    pub const ALL: [Position; 5] = [
40        Position::Top,
41        Position::Bottom,
42        Position::Left,
43        Position::Right,
44        Position::FollowCursor,
45    ];
46}
47
48/// Gap between the element and the bubble's margin, in logical pixels.
49pub const GAP: f32 = 6.0;
50
51/// The bubble's margin: the closest it comes to the window edges, and part
52/// of the space between it and its element.
53pub const EDGE: f32 = 5.0;
54
55/// Labels longer than this many characters are sentences rather than
56/// names, and read at [`text_size::SM`] instead of [`text_size::XS`].
57pub const LONG_LABEL: usize = 40;
58
59/// The text size of the bubble: `explicit` when set, otherwise small for a
60/// short label and a size up for a longer one.
61pub fn label_size(label: &str, explicit: Option<f32>) -> f32 {
62    if let Some(size) = explicit {
63        return size;
64    }
65    if label.chars().count() > LONG_LABEL {
66        return text_size::SM;
67    }
68    text_size::XS
69}
70
71/// A tooltip builder. Convert it into an [`Element`] to render.
72pub struct Tooltip<'a, Message> {
73    content: Element<'a, Message>,
74    label: text::Fragment<'a>,
75    position: Position,
76    delay: Duration,
77    max_width: Option<f32>,
78    text_size: Option<f32>,
79}
80
81impl<Message> std::fmt::Debug for Tooltip<'_, Message> {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.debug_struct("Tooltip")
84            .field("label", &self.label)
85            .field("position", &self.position)
86            .field("delay", &self.delay)
87            .field("max_width", &self.max_width)
88            .field("text_size", &self.text_size)
89            .finish_non_exhaustive()
90    }
91}
92
93/// Shows `label` in a bubble while the pointer is over `content`, or while
94/// something inside `content` has keyboard focus.
95pub fn tooltip<'a, Message>(
96    content: impl Into<Element<'a, Message>>,
97    label: impl text::IntoFragment<'a>,
98) -> Tooltip<'a, Message> {
99    Tooltip {
100        content: content.into(),
101        label: label.into_fragment(),
102        position: Position::default(),
103        delay: Duration::ZERO,
104        max_width: None,
105        text_size: None,
106    }
107}
108
109impl<'a, Message> Tooltip<'a, Message> {
110    pub fn position(mut self, position: Position) -> Self {
111        self.position = position;
112        self
113    }
114
115    /// How long the pointer has to rest before the bubble appears. Keyboard
116    /// focus shows it straight away.
117    pub fn delay(mut self, delay: Duration) -> Self {
118        self.delay = delay;
119        self
120    }
121
122    /// The widest the bubble grows, in logical pixels. A longer label wraps
123    /// onto more lines. Without it the bubble is as wide as the label, up
124    /// to the width of the window.
125    pub fn max_width(mut self, width: f32) -> Self {
126        self.max_width = Some(width);
127        self
128    }
129
130    /// The label's text size. Defaults to [`label_size`]: small for a few
131    /// words and a size up for a sentence.
132    pub fn text_size(mut self, size: f32) -> Self {
133        self.text_size = Some(size);
134        self
135    }
136}
137
138impl<'a, Message: 'a> From<Tooltip<'a, Message>> for Element<'a, Message> {
139    fn from(tooltip: Tooltip<'a, Message>) -> Self {
140        let size = label_size(&tooltip.label, tooltip.text_size);
141        #[cfg(feature = "icedwright")]
142        let label = tooltip.label.clone();
143        let mut bubble = container(text(tooltip.label).size(size))
144            .padding([space::XS + 2.0, space::MD])
145            .style(|theme| style(&Tokens::of(theme)));
146        if let Some(width) = tooltip.max_width {
147            bubble = bubble.max_width(width);
148        }
149        let bubble: Element<'a, Message> = bubble.into();
150        #[cfg(feature = "icedwright")]
151        let bubble = icedwright_probe::semantic(bubble)
152            .role(icedwright_probe::role::Tooltip)
153            .name(label.clone())
154            .component("iced_cube::tooltip")
155            .into();
156
157        after_touch(Element::new(Tip {
158            content: tooltip.content,
159            bubble,
160            position: tooltip.position,
161            delay: tooltip.delay,
162            #[cfg(feature = "icedwright")]
163            label,
164        }))
165    }
166}
167
168/// The bubble style: inverted colours so it stands out from the page.
169pub fn style(tokens: &Tokens) -> container::Style {
170    container::Style {
171        background: Some(Background::Color(tokens.primary)),
172        text_color: Some(tokens.primary_foreground),
173        border: Border {
174            radius: radius::MD.into(),
175            ..Border::default()
176        },
177        ..container::Style::default()
178    }
179}
180
181/// How focus reached the content, if it has it.
182#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
183pub enum Focus {
184    #[default]
185    None,
186    /// Focus came with a pointer press, so the bubble stays hidden.
187    Pointer,
188    /// Focus came any other way, such as Tab, and shows the bubble.
189    Keyboard,
190}
191
192impl Focus {
193    /// The focus after an event, given whether the content is `focused`
194    /// now and whether the event was a pointer press.
195    pub fn next(self, focused: bool, pointer_press: bool) -> Focus {
196        if !focused {
197            return Focus::None;
198        }
199        if pointer_press {
200            return Focus::Pointer;
201        }
202        if self == Focus::None {
203            return Focus::Keyboard;
204        }
205        self
206    }
207}
208
209/// Whether the pointer has shown the bubble.
210#[derive(Debug, Clone, Copy, PartialEq, Default)]
211enum Hover {
212    #[default]
213    Idle,
214    Resting {
215        at: Instant,
216    },
217    Open {
218        cursor: Point,
219    },
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Default)]
223struct State {
224    hover: Hover,
225    focus: Focus,
226}
227
228impl State {
229    fn shown(&self) -> bool {
230        matches!(self.hover, Hover::Open { .. }) || self.focus == Focus::Keyboard
231    }
232
233    fn cursor(&self) -> Option<Point> {
234        match self.hover {
235            Hover::Open { cursor } => Some(cursor),
236            _ => None,
237        }
238    }
239}
240
241fn is_pointer_press(event: &Event) -> bool {
242    matches!(
243        event,
244        Event::Mouse(mouse::Event::ButtonPressed(_))
245            | Event::Touch(touch::Event::FingerPressed { .. })
246    )
247}
248
249/// Whether focus may have changed with `event`. Pointer movement never
250/// moves focus, so it skips the check.
251fn may_move_focus(event: &Event) -> bool {
252    !matches!(
253        event,
254        Event::Mouse(mouse::Event::CursorMoved { .. } | mouse::Event::WheelScrolled { .. })
255            | Event::Touch(touch::Event::FingerMoved { .. })
256    )
257}
258
259/// Finds out whether any widget it visits has focus.
260#[derive(Debug, Default)]
261struct Probe {
262    focused: bool,
263}
264
265impl Operation for Probe {
266    fn traverse(&mut self, operate: &mut dyn FnMut(&mut dyn Operation)) {
267        operate(self);
268    }
269
270    fn focusable(
271        &mut self,
272        _id: Option<&widget::Id>,
273        _bounds: Rectangle,
274        state: &mut dyn Focusable,
275    ) {
276        self.focused |= state.is_focused();
277    }
278}
279
280struct Tip<'a, Message> {
281    content: Element<'a, Message>,
282    bubble: Element<'a, Message>,
283    position: Position,
284    delay: Duration,
285    #[cfg(feature = "icedwright")]
286    label: text::Fragment<'a>,
287}
288
289impl<Message> Tip<'_, Message> {
290    fn update_hover(
291        &self,
292        state: &mut State,
293        event: &Event,
294        layout: Layout<'_>,
295        cursor: mouse::Cursor,
296        shell: &mut Shell<'_, Message>,
297    ) {
298        if !matches!(
299            event,
300            Event::Mouse(_) | Event::Window(window::Event::RedrawRequested(_))
301        ) {
302            return;
303        }
304        let now = crate::time::now();
305        let over = cursor.position_over(layout.bounds());
306
307        match (state.hover, over) {
308            (Hover::Idle, Some(position)) => {
309                if self.delay == Duration::ZERO {
310                    state.hover = Hover::Open { cursor: position };
311                    shell.invalidate_layout();
312                } else {
313                    state.hover = Hover::Resting { at: now };
314                }
315                shell.request_redraw_at(now + self.delay);
316            }
317            (Hover::Resting { .. }, None) => state.hover = Hover::Idle,
318            (Hover::Resting { at }, _) if now.saturating_duration_since(at) < self.delay => {
319                shell.request_redraw_at(at + self.delay);
320            }
321            (Hover::Resting { .. }, Some(position)) => {
322                state.hover = Hover::Open { cursor: position };
323                shell.invalidate_layout();
324            }
325            (Hover::Open { cursor: last }, Some(position))
326                if self.position == Position::FollowCursor && last != position =>
327            {
328                state.hover = Hover::Open { cursor: position };
329                shell.request_redraw();
330            }
331            (Hover::Open { .. }, None) => {
332                state.hover = Hover::Idle;
333                shell.invalidate_layout();
334                if !matches!(event, Event::Window(window::Event::RedrawRequested(_))) {
335                    shell.request_redraw();
336                }
337            }
338            (Hover::Open { .. }, Some(_)) | (Hover::Idle, None) => {}
339        }
340    }
341}
342
343impl<Message> Widget<Message, Theme, Renderer> for Tip<'_, Message> {
344    fn size(&self) -> Size<Length> {
345        self.content.as_widget().size()
346    }
347
348    fn size_hint(&self) -> Size<Length> {
349        self.content.as_widget().size_hint()
350    }
351
352    fn tag(&self) -> tree::Tag {
353        tree::Tag::of::<State>()
354    }
355
356    fn state(&self) -> tree::State {
357        tree::State::new(State::default())
358    }
359
360    fn children(&self) -> Vec<Tree> {
361        vec![Tree::new(&self.content), Tree::new(&self.bubble)]
362    }
363
364    fn diff(&self, tree: &mut Tree) {
365        tree.diff_children(&[&self.content, &self.bubble]);
366    }
367
368    fn layout(
369        &mut self,
370        tree: &mut Tree,
371        renderer: &Renderer,
372        limits: &layout::Limits,
373    ) -> layout::Node {
374        self.content
375            .as_widget_mut()
376            .layout(&mut tree.children[0], renderer, limits)
377    }
378
379    fn draw(
380        &self,
381        tree: &Tree,
382        renderer: &mut Renderer,
383        theme: &Theme,
384        style: &renderer::Style,
385        layout: Layout<'_>,
386        cursor: mouse::Cursor,
387        viewport: &Rectangle,
388    ) {
389        self.content.as_widget().draw(
390            &tree.children[0],
391            renderer,
392            theme,
393            style,
394            layout,
395            cursor,
396            viewport,
397        );
398    }
399
400    fn operate(
401        &mut self,
402        tree: &mut Tree,
403        layout: Layout<'_>,
404        renderer: &Renderer,
405        operation: &mut dyn Operation,
406    ) {
407        #[cfg(feature = "icedwright")]
408        icedwright_probe::report(operation, layout.bounds(), || {
409            icedwright_probe::Annotation::new()
410                .tooltip(self.label.to_string())
411                .component("iced_cube::tooltip")
412        });
413        #[cfg(not(feature = "icedwright"))]
414        operation.container(None, layout.bounds());
415        operation.traverse(&mut |operation| {
416            self.content.as_widget_mut().operate(
417                &mut tree.children[0],
418                layout,
419                renderer,
420                operation,
421            );
422        });
423    }
424
425    fn update(
426        &mut self,
427        tree: &mut Tree,
428        event: &Event,
429        layout: Layout<'_>,
430        cursor: mouse::Cursor,
431        renderer: &Renderer,
432        clipboard: &mut dyn Clipboard,
433        shell: &mut Shell<'_, Message>,
434        viewport: &Rectangle,
435    ) {
436        let state = tree.state.downcast_mut::<State>();
437        let was_shown = state.shown();
438        self.update_hover(state, event, layout, cursor, shell);
439
440        let content = &mut tree.children[0];
441        self.content.as_widget_mut().update(
442            content, event, layout, cursor, renderer, clipboard, shell, viewport,
443        );
444        if !may_move_focus(event) {
445            return;
446        }
447
448        let mut probe = Probe::default();
449        self.content
450            .as_widget_mut()
451            .operate(content, layout, renderer, &mut probe);
452        let state = tree.state.downcast_mut::<State>();
453        state.focus = state.focus.next(probe.focused, is_pointer_press(event));
454        if state.shown() != was_shown {
455            shell.invalidate_layout();
456            shell.request_redraw();
457        }
458    }
459
460    fn mouse_interaction(
461        &self,
462        tree: &Tree,
463        layout: Layout<'_>,
464        cursor: mouse::Cursor,
465        viewport: &Rectangle,
466        renderer: &Renderer,
467    ) -> mouse::Interaction {
468        self.content.as_widget().mouse_interaction(
469            &tree.children[0],
470            layout,
471            cursor,
472            viewport,
473            renderer,
474        )
475    }
476
477    fn overlay<'b>(
478        &'b mut self,
479        tree: &'b mut Tree,
480        layout: Layout<'b>,
481        renderer: &Renderer,
482        viewport: &Rectangle,
483        translation: Vector,
484    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
485        let state = *tree.state.downcast_ref::<State>();
486        let [content_tree, bubble_tree] = tree.children.as_mut_slice() else {
487            return None;
488        };
489
490        let content = self.content.as_widget_mut().overlay(
491            content_tree,
492            layout,
493            renderer,
494            viewport,
495            translation,
496        );
497        let bubble = state.shown().then(|| {
498            overlay::Element::new(Box::new(Bubble {
499                position: layout.position() + translation,
500                content_bounds: layout.bounds(),
501                cursor: state.cursor(),
502                placement: self.position,
503                bubble: &mut self.bubble,
504                tree: bubble_tree,
505            }))
506        });
507
508        let children: Vec<_> = content.into_iter().chain(bubble).collect();
509        (!children.is_empty()).then(|| overlay::Group::with_children(children).overlay())
510    }
511}
512
513/// Where the bubble goes: its top left corner, given the content's
514/// position and bounds, the bubble's size and the pointer, before it is
515/// kept inside the window.
516fn place(
517    placement: Position,
518    position: Point,
519    content: Rectangle,
520    bubble: Size,
521    cursor: Option<Point>,
522) -> Point {
523    let x_centre = position.x + (content.width - bubble.width) / 2.0;
524    let y_centre = position.y + (content.height - bubble.height) / 2.0;
525    let gap = GAP + EDGE;
526    let above = Point::new(x_centre, position.y - bubble.height - gap);
527
528    match (placement, cursor) {
529        (Position::Top, _) | (Position::FollowCursor, None) => above,
530        (Position::Bottom, _) => Point::new(x_centre, position.y + content.height + gap),
531        (Position::Left, _) => Point::new(position.x - bubble.width - gap, y_centre),
532        (Position::Right, _) => Point::new(position.x + content.width + gap, y_centre),
533        (Position::FollowCursor, Some(cursor)) => {
534            let shift = position - content.position();
535            Point::new(cursor.x, cursor.y - bubble.height) + shift
536        }
537    }
538}
539
540/// The side the bubble goes on: `placement`, or the opposite side when
541/// `placement` would run out of `viewport` and the opposite would not, so
542/// a bubble near an edge is never pushed back over its own control.
543fn side_that_fits(
544    placement: Position,
545    position: Point,
546    content: Rectangle,
547    bubble: Size,
548    viewport: Rectangle,
549) -> Position {
550    // Only the side's own axis matters: sliding along the edge is left to
551    // `keep_inside`.
552    let fits = |side| {
553        let corner = place(side, position, content, bubble, None);
554        match side {
555            Position::Top | Position::Bottom => {
556                corner.y - EDGE >= viewport.y
557                    && corner.y + bubble.height + EDGE <= viewport.y + viewport.height
558            }
559            Position::Left | Position::Right | Position::FollowCursor => {
560                corner.x - EDGE >= viewport.x
561                    && corner.x + bubble.width + EDGE <= viewport.x + viewport.width
562            }
563        }
564    };
565    let opposite = match placement {
566        Position::Top => Position::Bottom,
567        Position::Bottom => Position::Top,
568        Position::Left => Position::Right,
569        Position::Right => Position::Left,
570        Position::FollowCursor => return placement,
571    };
572    if !fits(placement) && fits(opposite) {
573        return opposite;
574    }
575    placement
576}
577
578/// Moves `bounds` back inside `viewport`, leaving it where it is if it
579/// already fits.
580fn keep_inside(mut bounds: Rectangle, viewport: Rectangle) -> Rectangle {
581    if bounds.x < viewport.x {
582        bounds.x = viewport.x;
583    } else if viewport.x + viewport.width < bounds.x + bounds.width {
584        bounds.x = viewport.x + viewport.width - bounds.width;
585    }
586    if bounds.y < viewport.y {
587        bounds.y = viewport.y;
588    } else if viewport.y + viewport.height < bounds.y + bounds.height {
589        bounds.y = viewport.y + viewport.height - bounds.height;
590    }
591    bounds
592}
593
594struct Bubble<'a, 'b, Message> {
595    position: Point,
596    content_bounds: Rectangle,
597    cursor: Option<Point>,
598    placement: Position,
599    bubble: &'b mut Element<'a, Message>,
600    tree: &'b mut Tree,
601}
602
603impl<Message> overlay::Overlay<Message, Theme, Renderer> for Bubble<'_, '_, Message> {
604    fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node {
605        let viewport = Rectangle::with_size(bounds);
606        let limits = layout::Limits::new(Size::ZERO, viewport.size()).shrink(Padding::new(EDGE));
607        let node = self
608            .bubble
609            .as_widget_mut()
610            .layout(self.tree, renderer, &limits);
611        let size = node.size();
612
613        let side = side_that_fits(
614            self.placement,
615            self.position,
616            self.content_bounds,
617            size,
618            viewport,
619        );
620        let corner = place(side, self.position, self.content_bounds, size, self.cursor);
621        // The edge margin surrounds the bubble, so it never touches the
622        // window border once kept inside.
623        let framed = Rectangle {
624            x: corner.x - EDGE,
625            y: corner.y - EDGE,
626            width: size.width + EDGE * 2.0,
627            height: size.height + EDGE * 2.0,
628        };
629        let framed = keep_inside(framed, viewport);
630
631        layout::Node::with_children(framed.size(), vec![node.translate(Vector::new(EDGE, EDGE))])
632            .translate(Vector::new(framed.x, framed.y))
633    }
634
635    fn draw(
636        &self,
637        renderer: &mut Renderer,
638        theme: &Theme,
639        style: &renderer::Style,
640        layout: Layout<'_>,
641        cursor: mouse::Cursor,
642    ) {
643        let Some(bubble) = layout.children().next() else {
644            return;
645        };
646        self.bubble.as_widget().draw(
647            self.tree,
648            renderer,
649            theme,
650            style,
651            bubble,
652            cursor,
653            &Rectangle::with_size(Size::INFINITE),
654        );
655    }
656
657    fn operate(&mut self, layout: Layout<'_>, renderer: &Renderer, operation: &mut dyn Operation) {
658        let Some(bubble) = layout.children().next() else {
659            return;
660        };
661        self.bubble
662            .as_widget_mut()
663            .operate(self.tree, bubble, renderer, operation);
664    }
665}
666
667#[cfg(test)]
668mod tests {
669    use super::*;
670    use crate::theme::{dark, light};
671
672    #[test]
673    fn defaults_to_top_without_delay() {
674        let t: Tooltip<'_, ()> = tooltip(text("Hover"), "Hint");
675        assert_eq!(t.position, Position::Top);
676        assert_eq!(t.delay, Duration::ZERO);
677        assert_eq!(t.max_width, None);
678        assert_eq!(t.text_size, None);
679    }
680
681    #[test]
682    fn builder_sets_every_option() {
683        let t: Tooltip<'_, ()> = tooltip(text("Hover"), "Hint")
684            .position(Position::Left)
685            .delay(Duration::from_millis(300))
686            .max_width(240.0)
687            .text_size(13.0);
688        assert_eq!(t.position, Position::Left);
689        assert_eq!(t.delay, Duration::from_millis(300));
690        assert_eq!(t.max_width, Some(240.0));
691        assert_eq!(t.text_size, Some(13.0));
692    }
693
694    #[test]
695    fn bubble_inverts_the_page_in_both_themes() {
696        for theme in [light(), dark()] {
697            let tokens = Tokens::of(&theme);
698            let style = style(&tokens);
699            assert_eq!(style.background, Some(Background::Color(tokens.primary)));
700            assert_eq!(style.text_color, Some(tokens.primary_foreground));
701            assert_ne!(tokens.primary, tokens.background);
702        }
703    }
704
705    #[test]
706    fn short_labels_are_small_and_sentences_a_size_up() {
707        assert_eq!(label_size("Bold", None), text_size::XS);
708        assert_eq!(label_size(&"a".repeat(LONG_LABEL), None), text_size::XS);
709        assert_eq!(label_size(&"a".repeat(LONG_LABEL + 1), None), text_size::SM);
710        assert_eq!(label_size("Bold", Some(16.0)), 16.0);
711        assert_eq!(label_size(&"a".repeat(80), Some(11.0)), 11.0);
712    }
713
714    #[test]
715    fn keyboard_focus_shows_but_pointer_focus_does_not() {
716        assert_eq!(Focus::None.next(true, false), Focus::Keyboard);
717        assert_eq!(Focus::None.next(true, true), Focus::Pointer);
718        assert_eq!(Focus::Pointer.next(true, false), Focus::Pointer);
719        assert_eq!(Focus::Keyboard.next(true, false), Focus::Keyboard);
720        assert_eq!(Focus::Keyboard.next(true, true), Focus::Pointer);
721        for focus in [Focus::None, Focus::Pointer, Focus::Keyboard] {
722            assert_eq!(focus.next(false, false), Focus::None);
723            assert_eq!(focus.next(false, true), Focus::None);
724        }
725    }
726
727    #[test]
728    fn shown_while_hovered_or_keyboard_focused() {
729        let hovered = State {
730            hover: Hover::Open {
731                cursor: Point::ORIGIN,
732            },
733            focus: Focus::None,
734        };
735        assert!(hovered.shown());
736        assert_eq!(hovered.cursor(), Some(Point::ORIGIN));
737
738        let focused = State {
739            hover: Hover::Idle,
740            focus: Focus::Keyboard,
741        };
742        assert!(focused.shown());
743        assert_eq!(focused.cursor(), None);
744
745        assert!(!State::default().shown());
746        assert!(
747            !State {
748                focus: Focus::Pointer,
749                ..State::default()
750            }
751            .shown()
752        );
753    }
754
755    #[test]
756    fn bubble_sits_on_the_requested_side() {
757        let content = Rectangle::new(Point::new(100.0, 100.0), Size::new(40.0, 20.0));
758        let bubble = Size::new(60.0, 24.0);
759        let at = |placement, cursor| place(placement, content.position(), content, bubble, cursor);
760        let gap = GAP + EDGE;
761
762        assert_eq!(
763            at(Position::Top, None),
764            Point::new(90.0, 100.0 - 24.0 - gap)
765        );
766        assert_eq!(at(Position::Bottom, None), Point::new(90.0, 120.0 + gap));
767        assert_eq!(
768            at(Position::Left, None),
769            Point::new(100.0 - 60.0 - gap, 98.0)
770        );
771        assert_eq!(at(Position::Right, None), Point::new(140.0 + gap, 98.0));
772        assert_eq!(
773            at(Position::FollowCursor, Some(Point::new(110.0, 105.0))),
774            Point::new(110.0, 81.0)
775        );
776        assert_eq!(
777            at(Position::FollowCursor, None),
778            at(Position::Top, None),
779            "keyboard focus has no pointer to follow"
780        );
781    }
782
783    #[test]
784    fn a_bubble_with_no_room_flips_to_the_other_side() {
785        let window = Rectangle::with_size(Size::new(300.0, 200.0));
786        let bubble = Size::new(60.0, 24.0);
787        let side = |placement, content: Rectangle| {
788            side_that_fits(placement, content.position(), content, bubble, window)
789        };
790        let middle = Rectangle::new(Point::new(120.0, 90.0), Size::new(40.0, 20.0));
791        for placement in [
792            Position::Top,
793            Position::Bottom,
794            Position::Left,
795            Position::Right,
796        ] {
797            assert_eq!(side(placement, middle), placement);
798        }
799        let top_right = Rectangle::new(Point::new(256.0, 4.0), Size::new(40.0, 20.0));
800        assert_eq!(side(Position::Top, top_right), Position::Bottom);
801        assert_eq!(side(Position::Right, top_right), Position::Left);
802        let bottom_left = Rectangle::new(Point::new(4.0, 176.0), Size::new(40.0, 20.0));
803        assert_eq!(side(Position::Bottom, bottom_left), Position::Top);
804        assert_eq!(side(Position::Left, bottom_left), Position::Right);
805        assert_eq!(
806            side(Position::FollowCursor, top_right),
807            Position::FollowCursor
808        );
809    }
810
811    #[test]
812    fn bubble_is_kept_inside_the_window() {
813        let window = Rectangle::with_size(Size::new(200.0, 100.0));
814        let inside = Rectangle::new(Point::new(10.0, 10.0), Size::new(50.0, 20.0));
815        assert_eq!(keep_inside(inside, window), inside);
816
817        let left = Rectangle::new(Point::new(-20.0, -5.0), Size::new(50.0, 20.0));
818        assert_eq!(keep_inside(left, window).position(), Point::ORIGIN);
819
820        let right = Rectangle::new(Point::new(180.0, 90.0), Size::new(50.0, 20.0));
821        assert_eq!(
822            keep_inside(right, window).position(),
823            Point::new(150.0, 80.0)
824        );
825    }
826}