1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
use iced::{
    layout, Clipboard, Element, Event, Hasher, Layout, Length, Point, Rectangle, Size, Widget,
};
use std::{
    hash::Hash,
    sync::Mutex,
    time::{Duration, Instant},
};
use vek::*;

#[derive(Copy, Clone, Debug)]
struct Hover {
    start: Instant,
    aabr: Aabr<i32>,
}

impl Hover {
    fn start(aabr: Aabr<i32>) -> Self {
        Self {
            start: Instant::now(),
            aabr,
        }
    }
}

#[derive(Copy, Clone, Debug)]
struct Show {
    hover_pos: Vec2<i32>,
    aabr: Aabr<i32>,
}

#[derive(Copy, Clone, Debug)]
enum State {
    Idle,
    Start(Hover),
    Showing(Show),
    Fading(Instant, Show, Option<Hover>),
}

// Reports which widget the mouse is over
#[derive(Copy, Clone, Debug)]
struct Update((Aabr<i32>, Vec2<i32>));

#[derive(Debug)]
// TODO: consider moving all this state into the Renderer
pub struct TooltipManager {
    state: State,
    update: Mutex<Option<Update>>,
    hover_pos: Vec2<i32>,
    // How long before a tooltip is displayed when hovering
    hover_dur: Duration,
    // How long it takes a tooltip to disappear
    fade_dur: Duration,
}

impl TooltipManager {
    pub fn new(hover_dur: Duration, fade_dur: Duration) -> Self {
        Self {
            state: State::Idle,
            update: Mutex::new(None),
            hover_pos: Default::default(),
            hover_dur,
            fade_dur,
        }
    }

    /// Call this at the top of your view function or for minimum latency at the
    /// end of message handling
    /// that there is no tooltipped widget currently being hovered
    pub fn maintain(&mut self) {
        let update = self.update.get_mut().unwrap().take();
        // Handle changes based on pointer moving
        self.state = if let Some(Update((aabr, hover_pos))) = update {
            self.hover_pos = hover_pos;
            match self.state {
                State::Idle => State::Start(Hover::start(aabr)),
                State::Start(hover) if hover.aabr != aabr => State::Start(Hover::start(aabr)),
                State::Start(hover) => State::Start(hover),
                State::Showing(show) if show.aabr != aabr => {
                    State::Fading(Instant::now(), show, Some(Hover::start(aabr)))
                },
                State::Showing(show) => State::Showing(show),
                State::Fading(start, show, Some(hover)) if hover.aabr == aabr => {
                    State::Fading(start, show, Some(hover))
                },
                State::Fading(start, show, _) => {
                    State::Fading(start, show, Some(Hover::start(aabr)))
                },
            }
        } else {
            match self.state {
                State::Idle | State::Start(_) => State::Idle,
                State::Showing(show) => State::Fading(Instant::now(), show, None),
                State::Fading(start, show, _) => State::Fading(start, show, None),
            }
        };

        // Handle temporal changes
        self.state = match self.state {
            State::Start(Hover { start, aabr })
            | State::Fading(_, _, Some(Hover { start, aabr }))
                if start.elapsed() >= self.hover_dur =>
            {
                State::Showing(Show {
                    aabr,
                    hover_pos: self.hover_pos,
                })
            },
            State::Fading(start, _, hover) if start.elapsed() >= self.fade_dur => match hover {
                Some(hover) => State::Start(hover),
                None => State::Idle,
            },
            state @ State::Idle
            | state @ State::Start(_)
            | state @ State::Showing(_)
            | state @ State::Fading(_, _, _) => state,
        };
    }

    fn update(&self, update: Update) { *self.update.lock().unwrap() = Some(update); }

    /// Returns an options with the position of the cursor when the tooltip
    /// started being show and the transparency if it is fading
    fn showing(&self, aabr: Aabr<i32>) -> Option<(Point, f32)> {
        match self.state {
            State::Idle | State::Start(_) => None,
            State::Showing(show) => (show.aabr == aabr).then_some({
                (
                    Point {
                        x: show.hover_pos.x as f32,
                        y: show.hover_pos.y as f32,
                    },
                    1.0,
                )
            }),
            State::Fading(start, show, _) => (show.aabr == aabr)
                .then(|| {
                    (
                        Point {
                            x: show.hover_pos.x as f32,
                            y: show.hover_pos.y as f32,
                        },
                        1.0 - start.elapsed().as_secs_f32() / self.fade_dur.as_secs_f32(),
                    )
                })
                .filter(|(_, fade)| *fade > 0.0),
        }
    }
}

/// A widget used to display tooltips when the content element is hovered
pub struct Tooltip<'a, M, R: Renderer> {
    content: Element<'a, M, R>,
    hover_content: Box<dyn 'a + FnMut() -> Element<'a, M, R>>,
    manager: &'a TooltipManager,
}

impl<'a, M, R> Tooltip<'a, M, R>
where
    R: Renderer,
{
    pub fn new<C, H>(content: C, hover_content: H, manager: &'a TooltipManager) -> Self
    where
        C: Into<Element<'a, M, R>>,
        H: 'a + FnMut() -> Element<'a, M, R>,
    {
        Self {
            content: content.into(),
            hover_content: Box::new(hover_content),
            manager,
        }
    }
}

impl<'a, M, R> Widget<M, R> for Tooltip<'a, M, R>
where
    R: Renderer,
{
    fn width(&self) -> Length { self.content.width() }

    fn height(&self) -> Length { self.content.height() }

    fn layout(&self, renderer: &R, limits: &layout::Limits) -> layout::Node {
        self.content.layout(renderer, limits)
    }

    fn draw(
        &self,
        renderer: &mut R,
        defaults: &R::Defaults,
        layout: Layout<'_>,
        cursor_position: Point,
        viewport: &Rectangle,
    ) -> R::Output {
        let bounds = layout.bounds();
        if bounds.contains(cursor_position) {
            // TODO: these bounds aren't actually global (for example see how the Scrollable
            // widget handles its content) so it's not actually a good key to
            // use here
            let aabr = aabr_from_bounds(bounds);
            let m_pos = Vec2::new(
                cursor_position.x.trunc() as i32,
                cursor_position.y.trunc() as i32,
            );
            self.manager.update(Update((aabr, m_pos)));
        }

        self.content
            .draw(renderer, defaults, layout, cursor_position, viewport)
    }

    fn hash_layout(&self, state: &mut Hasher) {
        struct Marker;
        std::any::TypeId::of::<Marker>().hash(state);
        self.content.hash_layout(state);
    }

    fn on_event(
        &mut self,
        event: Event,
        layout: Layout<'_>,
        cursor_position: Point,
        renderer: &R,
        clipboard: &mut dyn Clipboard,
        messages: &mut Vec<M>,
    ) -> iced::event::Status {
        self.content.on_event(
            event,
            layout,
            cursor_position,
            renderer,
            clipboard,
            messages,
        )
    }

    fn overlay(&mut self, layout: Layout<'_>) -> Option<iced::overlay::Element<'_, M, R>> {
        let bounds = layout.bounds();
        let aabr = aabr_from_bounds(bounds);

        self.manager.showing(aabr).map(|(cursor_pos, alpha)| {
            iced::overlay::Element::new(
                Point::ORIGIN,
                Box::new(Overlay::new(
                    (self.hover_content)(),
                    cursor_pos,
                    bounds,
                    alpha,
                )),
            )
        })
    }
}

impl<'a, M, R> From<Tooltip<'a, M, R>> for Element<'a, M, R>
where
    R: 'a + Renderer,
    M: 'a,
{
    fn from(tooltip: Tooltip<'a, M, R>) -> Element<'a, M, R> { Element::new(tooltip) }
}

fn aabr_from_bounds(bounds: Rectangle) -> Aabr<i32> {
    let min = Vec2::new(bounds.x.trunc() as i32, bounds.y.trunc() as i32);
    let max = min + Vec2::new(bounds.width.trunc() as i32, bounds.height.trunc() as i32);
    Aabr { min, max }
}

struct Overlay<'a, M, R: Renderer> {
    content: Element<'a, M, R>,
    /// Cursor position
    cursor_position: Point,
    /// Area to avoid overlapping with
    avoid: Rectangle,
    /// Alpha for fading out
    alpha: f32,
}

impl<'a, M, R: Renderer> Overlay<'a, M, R> {
    pub fn new(
        content: Element<'a, M, R>,
        cursor_position: Point,
        avoid: Rectangle,
        alpha: f32,
    ) -> Self {
        Self {
            content,
            cursor_position,
            avoid,
            alpha,
        }
    }
}

impl<'a, M, R> iced::Overlay<M, R> for Overlay<'a, M, R>
where
    R: Renderer,
{
    fn layout(&self, renderer: &R, bounds: Size, position: Point) -> layout::Node {
        let avoid = Rectangle {
            x: self.avoid.x + position.x,
            y: self.avoid.y + position.y,
            ..self.avoid
        };
        let cursor_position = Point {
            x: self.cursor_position.x + position.x,
            y: self.cursor_position.y + position.y,
        };

        const PAD: f32 = 8.0; // TODO: allow configuration
        let space_above = (avoid.y - PAD).max(0.0);
        let space_below = (bounds.height - avoid.y - avoid.height - PAD).max(0.0);

        let limits = layout::Limits::new(
            Size::ZERO,
            Size::new(bounds.width, space_above.max(space_below)),
        );

        let mut node = self.content.layout(renderer, &limits);

        let size = node.size();

        node.move_to(Point {
            x: (bounds.width - size.width).min(cursor_position.x),
            y: if space_above >= space_below {
                avoid.y - size.height - PAD
            } else {
                avoid.y + avoid.height + PAD
            },
        });

        node
    }

    fn draw(
        &self,
        renderer: &mut R,
        defaults: &R::Defaults,
        layout: Layout<'_>,
        cursor_position: Point,
    ) -> R::Output {
        renderer.draw(
            self.alpha,
            defaults,
            cursor_position,
            &layout.bounds(),
            &self.content,
            layout,
        )
    }

    fn hash_layout(&self, state: &mut Hasher, position: Point) {
        struct Marker;
        std::any::TypeId::of::<Marker>().hash(state);

        (position.x as u32).hash(state);
        (position.y as u32).hash(state);
        (self.cursor_position.x as u32).hash(state);
        (self.avoid.x as u32).hash(state);
        (self.avoid.y as u32).hash(state);
        (self.avoid.height as u32).hash(state);
        (self.avoid.width as u32).hash(state);
        self.content.hash_layout(state);
    }
}

pub trait Renderer: iced::Renderer {
    fn draw<M>(
        &mut self,
        alpha: f32,
        defaults: &Self::Defaults,
        cursor_position: Point,
        viewport: &Rectangle,
        content: &Element<'_, M, Self>,
        content_layout: Layout<'_>,
    ) -> Self::Output;
}