cosmic/widget/
popover.rs

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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Copyright 2022 System76 <info@system76.com>
// SPDX-License-Identifier: MPL-2.0

//! A widget showing a popup in an overlay positioned relative to another widget.

use iced_core::event::{self, Event};
use iced_core::layout;
use iced_core::mouse;
use iced_core::overlay;
use iced_core::renderer;
use iced_core::touch;
use iced_core::widget::{tree, Operation, Tree};
use iced_core::{
    Clipboard, Element, Layout, Length, Point, Rectangle, Shell, Size, Vector, Widget,
};

pub use iced_widget::container::{Catalog, Style};

pub fn popover<'a, Message, Renderer>(
    content: impl Into<Element<'a, Message, crate::Theme, Renderer>>,
) -> Popover<'a, Message, Renderer> {
    Popover::new(content)
}

#[derive(Clone, Copy, Debug, Default)]
pub enum Position {
    #[default]
    Center,
    Bottom,
    Point(Point),
}

#[must_use]
pub struct Popover<'a, Message, Renderer> {
    content: Element<'a, Message, crate::Theme, Renderer>,
    modal: bool,
    popup: Option<Element<'a, Message, crate::Theme, Renderer>>,
    position: Position,
    on_close: Option<Message>,
}

impl<'a, Message, Renderer> Popover<'a, Message, Renderer> {
    pub fn new(content: impl Into<Element<'a, Message, crate::Theme, Renderer>>) -> Self {
        Self {
            content: content.into(),
            modal: false,
            popup: None,
            position: Position::Center,
            on_close: None,
        }
    }

    /// A modal popup interrupts user inputs and demands action.
    pub fn modal(mut self, modal: bool) -> Self {
        self.modal = modal;
        self
    }

    /// Emitted when the popup is closed.
    pub fn on_close(mut self, on_close: Message) -> Self {
        self.on_close = Some(on_close);
        self
    }

    pub fn popup(mut self, popup: impl Into<Element<'a, Message, crate::Theme, Renderer>>) -> Self {
        self.popup = Some(popup.into());
        self
    }

    pub fn position(mut self, position: Position) -> Self {
        self.position = position;
        self
    }

    // TODO More options for positioning similar to GdkPopup, xdg_popup
}

impl<'a, Message: Clone, Renderer> Widget<Message, crate::Theme, Renderer>
    for Popover<'a, Message, Renderer>
where
    Renderer: iced_core::Renderer,
{
    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<State>()
    }

    fn state(&self) -> tree::State {
        tree::State::new(State { is_open: true })
    }

    fn children(&self) -> Vec<Tree> {
        if let Some(popup) = &self.popup {
            vec![Tree::new(&self.content), Tree::new(popup)]
        } else {
            vec![Tree::new(&self.content)]
        }
    }

    fn diff(&mut self, tree: &mut Tree) {
        if let Some(popup) = &mut self.popup {
            tree.diff_children(&mut [&mut self.content, popup]);
        } else {
            tree.diff_children(&mut [&mut self.content]);
        }
    }

    fn size(&self) -> Size<Length> {
        self.content.as_widget().size()
    }

    fn layout(
        &self,
        tree: &mut Tree,
        renderer: &Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        let tree = &mut tree.children[0];
        self.content.as_widget().layout(tree, renderer, limits)
    }

    fn operate(
        &self,
        tree: &mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation<()>,
    ) {
        self.content
            .as_widget()
            .operate(&mut tree.children[0], layout, renderer, operation);
    }

    fn on_event(
        &mut self,
        tree: &mut Tree,
        event: Event,
        layout: Layout<'_>,
        cursor_position: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        viewport: &Rectangle,
    ) -> event::Status {
        if !self.modal
            && matches!(
                event,
                Event::Mouse(mouse::Event::ButtonPressed(_))
                    | Event::Touch(touch::Event::FingerPressed { .. })
            )
        {
            let state = tree.state.downcast_mut::<State>();
            let was_open = state.is_open;
            state.is_open = cursor_position.is_over(layout.bounds());

            if let Some(on_close) = self.on_close.clone() {
                if was_open && !state.is_open {
                    shell.publish(on_close);
                }
            }
        }

        self.content.as_widget_mut().on_event(
            &mut tree.children[0],
            event,
            layout,
            cursor_position,
            renderer,
            clipboard,
            shell,
            viewport,
        )
    }

    fn mouse_interaction(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        cursor_position: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        self.content.as_widget().mouse_interaction(
            &tree.children[0],
            layout,
            cursor_position,
            viewport,
            renderer,
        )
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut Renderer,
        theme: &crate::Theme,
        renderer_style: &renderer::Style,
        layout: Layout<'_>,
        cursor_position: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        self.content.as_widget().draw(
            &tree.children[0],
            renderer,
            theme,
            renderer_style,
            layout,
            cursor_position,
            viewport,
        );
    }

    fn overlay<'b>(
        &'b mut self,
        tree: &'b mut Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        mut translation: Vector,
    ) -> Option<overlay::Element<'b, Message, crate::Theme, Renderer>> {
        if !tree.state.downcast_mut::<State>().is_open {
            return None;
        }

        if let Some(popup) = &mut self.popup {
            let bounds = layout.bounds();

            // Calculate overlay position from relative position
            let mut overlay_position = match self.position {
                Position::Center => Point::new(
                    bounds.x + bounds.width / 2.0,
                    bounds.y + bounds.height / 2.0,
                ),
                Position::Bottom => {
                    Point::new(bounds.x + bounds.width / 2.0, bounds.y + bounds.height)
                }
                Position::Point(relative) => {
                    bounds.position() + Vector::new(relative.x, relative.y)
                }
            };

            // Round position to prevent rendering issues
            overlay_position.x = overlay_position.x.round();
            overlay_position.y = overlay_position.y.round();
            translation.x += overlay_position.x;
            translation.y += overlay_position.y;

            Some(overlay::Element::new(Box::new(Overlay {
                tree: &mut tree.children[1],
                content: popup,
                position: self.position,
                pos: Point::new(translation.x, translation.y),
            })))
        } else {
            self.content.as_widget_mut().overlay(
                &mut tree.children[0],
                layout,
                renderer,
                translation,
            )
        }
    }

    fn drag_destinations(
        &self,
        tree: &Tree,
        layout: Layout<'_>,
        renderer: &Renderer,
        dnd_rectangles: &mut iced_core::clipboard::DndDestinationRectangles,
    ) {
        self.content.as_widget().drag_destinations(
            &tree.children[0],
            layout,
            renderer,
            dnd_rectangles,
        );
    }

    #[cfg(feature = "a11y")]
    /// get the a11y nodes for the widget
    fn a11y_nodes(
        &self,
        layout: Layout<'_>,
        state: &Tree,
        p: mouse::Cursor,
    ) -> iced_accessibility::A11yTree {
        let c_state = &state.children[0];
        self.content.as_widget().a11y_nodes(layout, c_state, p)
    }
}

impl<'a, Message, Renderer> From<Popover<'a, Message, Renderer>>
    for Element<'a, Message, crate::Theme, Renderer>
where
    Message: 'static + Clone,
    Renderer: iced_core::Renderer + 'static,
{
    fn from(popover: Popover<'a, Message, Renderer>) -> Self {
        Self::new(popover)
    }
}

pub struct Overlay<'a, 'b, Message, Renderer> {
    tree: &'a mut Tree,
    content: &'a mut Element<'b, Message, crate::Theme, Renderer>,
    position: Position,
    pos: Point,
}

impl<'a, 'b, Message, Renderer> overlay::Overlay<Message, crate::Theme, Renderer>
    for Overlay<'a, 'b, Message, Renderer>
where
    Message: Clone,
    Renderer: iced_core::Renderer,
{
    fn layout(&mut self, renderer: &Renderer, bounds: Size) -> layout::Node {
        let mut position = self.pos;
        let limits = layout::Limits::new(Size::UNIT, bounds);
        let node = self
            .content
            .as_widget()
            .layout(self.tree, renderer, &limits);
        match self.position {
            Position::Center => {
                // Position is set to the center of the widget
                let width = node.size().width;
                let height = node.size().height;
                position.x = (position.x - width / 2.0).clamp(0.0, bounds.width - width);
                position.y = (position.y - height / 2.0).clamp(0.0, bounds.height - height);
            }
            Position::Bottom => {
                // Position is set to the center bottom of the widget
                let width = node.size().width;
                let height = node.size().height;
                position.x = (position.x - width / 2.0).clamp(0.0, bounds.width - width);
                position.y = position.y.clamp(0.0, bounds.height - height);
            }
            Position::Point(_) => {
                // Position is using context menu logic
                let size = node.size();
                position.x = position.x.clamp(0.0, bounds.width - size.width);
                if position.y + size.height > bounds.height {
                    position.y = (position.y - size.height).clamp(0.0, bounds.height - size.height);
                }
            }
        }

        // Round position to prevent rendering issues
        position.x = position.x.round();
        position.y = position.y.round();

        node.move_to(position)
    }

    fn operate(
        &mut self,
        layout: Layout<'_>,
        renderer: &Renderer,
        operation: &mut dyn Operation<()>,
    ) {
        self.content
            .as_widget()
            .operate(self.tree, layout, renderer, operation);
    }

    fn on_event(
        &mut self,
        event: Event,
        layout: Layout<'_>,
        cursor_position: mouse::Cursor,
        renderer: &Renderer,
        clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
    ) -> event::Status {
        self.content.as_widget_mut().on_event(
            self.tree,
            event,
            layout,
            cursor_position,
            renderer,
            clipboard,
            shell,
            &layout.bounds(),
        )
    }

    fn mouse_interaction(
        &self,
        layout: Layout<'_>,
        cursor_position: mouse::Cursor,
        viewport: &Rectangle,
        renderer: &Renderer,
    ) -> mouse::Interaction {
        self.content.as_widget().mouse_interaction(
            self.tree,
            layout,
            cursor_position,
            viewport,
            renderer,
        )
    }

    fn draw(
        &self,
        renderer: &mut Renderer,
        theme: &crate::Theme,
        style: &renderer::Style,
        layout: Layout<'_>,
        cursor_position: mouse::Cursor,
    ) {
        let bounds = layout.bounds();
        self.content.as_widget().draw(
            self.tree,
            renderer,
            theme,
            style,
            layout,
            cursor_position,
            &bounds,
        );
    }

    fn overlay<'c>(
        &'c mut self,
        layout: Layout<'_>,
        renderer: &Renderer,
    ) -> Option<overlay::Element<'c, Message, crate::Theme, Renderer>> {
        self.content
            .as_widget_mut()
            .overlay(&mut self.tree, layout, renderer, Default::default())
    }
}

/// The local state of a [`Popover`].
#[derive(Debug, Default)]
struct State {
    is_open: bool,
}