Skip to main content

cosmic/widget/dropdown/menu/
mod.rs

1// Copyright 2023 System76 <info@system76.com>
2// Copyright 2019 Héctor Ramón, Iced contributors
3// SPDX-License-Identifier: MPL-2.0 AND MIT
4
5mod appearance;
6use std::borrow::Cow;
7use std::sync::{Arc, Mutex};
8
9pub use appearance::{Appearance, StyleSheet};
10
11use crate::widget::{Container, RcWrapper, icon};
12use iced_core::event::Event;
13use iced_core::layout::{self, Layout};
14use iced_core::text::{self, Text};
15use iced_core::widget::Tree;
16use iced_core::{
17    Border, Clipboard, Element, Length, Padding, Pixels, Point, Rectangle, Renderer, Shadow, Shell,
18    Size, Vector, Widget, alignment, mouse, overlay, renderer, svg, touch,
19};
20use iced_widget::scrollable::Scrollable;
21
22/// A list of selectable options.
23#[must_use]
24pub struct Menu<'a, S, Message>
25where
26    S: AsRef<str>,
27    [S]: std::borrow::ToOwned,
28{
29    state: State,
30    options: Cow<'a, [S]>,
31    icons: Cow<'a, [icon::Handle]>,
32    hovered_option: Arc<Mutex<Option<usize>>>,
33    selected_option: Option<usize>,
34    on_selected: Box<dyn FnMut(usize) -> Message + 'a>,
35    close_on_selected: Option<Message>,
36    on_option_hovered: Option<&'a dyn Fn(usize) -> Message>,
37    width: f32,
38    padding: Padding,
39    text_size: Option<f32>,
40    text_line_height: text::LineHeight,
41    style: (),
42}
43
44impl<'a, S: AsRef<str>, Message: 'a + std::clone::Clone> Menu<'a, S, Message>
45where
46    [S]: std::borrow::ToOwned,
47{
48    /// Creates a new [`Menu`] with the given [`State`], a list of options, and
49    /// the message to produced when an option is selected.
50    pub fn new(
51        state: State,
52        options: Cow<'a, [S]>,
53        icons: Cow<'a, [icon::Handle]>,
54        hovered_option: Arc<Mutex<Option<usize>>>,
55        selected_option: Option<usize>,
56        on_selected: impl FnMut(usize) -> Message + 'a,
57        on_option_hovered: Option<&'a dyn Fn(usize) -> Message>,
58        close_on_selected: Option<Message>,
59    ) -> Self {
60        Menu {
61            state,
62            options,
63            icons,
64            hovered_option,
65            selected_option,
66            on_selected: Box::new(on_selected),
67            on_option_hovered,
68            width: 0.0,
69            padding: Padding::ZERO,
70            text_size: None,
71            text_line_height: text::LineHeight::default(),
72            style: Default::default(),
73            close_on_selected,
74        }
75    }
76
77    /// Sets the width of the [`Menu`].
78    pub fn width(mut self, width: f32) -> Self {
79        self.width = width;
80        self
81    }
82
83    /// Sets the [`Padding`] of the [`Menu`].
84    pub fn padding<P: Into<Padding>>(mut self, padding: P) -> Self {
85        self.padding = padding.into();
86        self
87    }
88
89    /// Sets the text size of the [`Menu`].
90    pub fn text_size(mut self, text_size: impl Into<Pixels>) -> Self {
91        self.text_size = Some(text_size.into().0);
92        self
93    }
94
95    /// Sets the text [`LineHeight`] of the [`Menu`].
96    pub fn text_line_height(mut self, line_height: impl Into<text::LineHeight>) -> Self {
97        self.text_line_height = line_height.into();
98        self
99    }
100
101    /// Turns the [`Menu`] into an overlay [`Element`] at the given target
102    /// position.
103    ///
104    /// The `target_height` will be used to display the menu either on top
105    /// of the target or under it, depending on the screen position and the
106    /// dimensions of the [`Menu`].
107    #[must_use]
108    pub fn overlay(
109        self,
110        position: Point,
111        target_height: f32,
112    ) -> overlay::Element<'a, Message, crate::Theme, crate::Renderer> {
113        overlay::Element::new(Box::new(Overlay::new(self, target_height, position)))
114    }
115
116    /// Turns the [`Menu`] into a popup [`Element`] at the given target
117    /// position.
118    ///
119    /// The `target_height` will be used to display the menu either on top
120    /// of the target or under it, depending on the screen position and the
121    /// dimensions of the [`Menu`].
122    #[must_use]
123    pub fn popup(self, position: Point, target_height: f32) -> crate::Element<'a, Message> {
124        Overlay::new(self, target_height, position).into()
125    }
126}
127
128/// The local state of a [`Menu`].
129#[must_use]
130#[derive(Debug, Clone)]
131pub struct State {
132    pub(crate) tree: RcWrapper<Tree>,
133}
134
135impl State {
136    /// Creates a new [`State`] for a [`Menu`].
137    pub fn new() -> Self {
138        Self {
139            tree: RcWrapper::new(Tree::empty()),
140        }
141    }
142}
143
144impl Default for State {
145    fn default() -> Self {
146        Self::new()
147    }
148}
149
150struct Overlay<'a, Message> {
151    state: RcWrapper<Tree>,
152    container: Container<'a, Message, crate::Theme, crate::Renderer>,
153    width: f32,
154    target_height: f32,
155    style: (),
156    position: Point,
157}
158
159impl<'a, Message: Clone + 'a> Overlay<'a, Message> {
160    pub fn new<S: AsRef<str>>(
161        menu: Menu<'a, S, Message>,
162        target_height: f32,
163        position: Point,
164    ) -> Self
165    where
166        [S]: ToOwned,
167    {
168        let Menu {
169            state,
170            options,
171            icons,
172            hovered_option,
173            selected_option,
174            on_selected,
175            on_option_hovered,
176            width,
177            padding,
178            text_size,
179            text_line_height,
180            style,
181            close_on_selected,
182        } = menu;
183
184        let mut container = Container::new(Scrollable::new(
185            Container::new(List {
186                options,
187                icons,
188                hovered_option,
189                selected_option,
190                on_selected,
191                close_on_selected,
192                on_option_hovered,
193                text_size,
194                text_line_height,
195                padding,
196            })
197            .padding(padding),
198        ))
199        .class(crate::style::Container::Dropdown);
200
201        state
202            .tree
203            .with_data_mut(|tree| tree.diff(&mut container as &mut dyn Widget<_, _, _>));
204
205        Self {
206            state: state.tree,
207            container,
208            width,
209            target_height,
210            style,
211            position,
212        }
213    }
214
215    fn _layout(&mut self, renderer: &crate::Renderer, bounds: Size) -> layout::Node {
216        let space_below = bounds.height - (self.position.y + self.target_height);
217        let space_above = self.position.y;
218
219        let limits = layout::Limits::new(
220            Size::ZERO,
221            Size::new(
222                bounds.width - self.position.x,
223                if space_below > space_above {
224                    space_below
225                } else {
226                    space_above
227                },
228            ),
229        )
230        .width(self.width);
231
232        let node = self
233            .state
234            .with_data_mut(|tree| self.container.layout(tree, renderer, &limits));
235
236        let node_size = node.size();
237        node.move_to(if space_below > space_above {
238            self.position + Vector::new(0.0, self.target_height)
239        } else {
240            self.position - Vector::new(0.0, node_size.height)
241        })
242    }
243
244    fn _update(
245        &mut self,
246        event: &Event,
247        layout: Layout<'_>,
248        cursor: mouse::Cursor,
249        renderer: &crate::Renderer,
250        clipboard: &mut dyn Clipboard,
251        shell: &mut Shell<'_, Message>,
252    ) {
253        let bounds = layout.bounds();
254
255        self.state.with_data_mut(|tree| {
256            self.container.update(
257                tree, event, layout, cursor, renderer, clipboard, shell, &bounds,
258            )
259        })
260    }
261
262    fn _mouse_interaction(
263        &self,
264        layout: Layout<'_>,
265        cursor: mouse::Cursor,
266        viewport: &Rectangle,
267        renderer: &crate::Renderer,
268    ) -> mouse::Interaction {
269        self.state.with_data(|tree| {
270            self.container
271                .mouse_interaction(tree, layout, cursor, viewport, renderer)
272        })
273    }
274
275    fn _draw(
276        &self,
277        renderer: &mut crate::Renderer,
278        theme: &crate::Theme,
279        style: &renderer::Style,
280        layout: Layout<'_>,
281        cursor: mouse::Cursor,
282    ) {
283        let appearance = theme.appearance(&self.style);
284        let bounds = layout.bounds();
285
286        renderer.fill_quad(
287            renderer::Quad {
288                bounds,
289                border: Border {
290                    width: appearance.border_width,
291                    color: appearance.border_color,
292                    radius: appearance.border_radius,
293                },
294                shadow: Shadow::default(),
295                snap: true,
296            },
297            appearance.background,
298        );
299
300        self.state.with_data(|tree| {
301            self.container
302                .draw(tree, renderer, theme, style, layout, cursor, &bounds)
303        })
304    }
305}
306
307impl<'a, Message: Clone + 'a> iced_core::Overlay<Message, crate::Theme, crate::Renderer>
308    for Overlay<'a, Message>
309{
310    fn layout(&mut self, renderer: &crate::Renderer, bounds: Size) -> layout::Node {
311        self._layout(renderer, bounds)
312    }
313
314    fn update(
315        &mut self,
316        event: &Event,
317        layout: Layout<'_>,
318        cursor: mouse::Cursor,
319        renderer: &crate::Renderer,
320        clipboard: &mut dyn Clipboard,
321        shell: &mut Shell<'_, Message>,
322    ) {
323        self._update(event, layout, cursor, renderer, clipboard, shell)
324    }
325
326    fn mouse_interaction(
327        &self,
328        layout: Layout<'_>,
329        cursor: mouse::Cursor,
330        renderer: &crate::Renderer,
331    ) -> mouse::Interaction {
332        self._mouse_interaction(layout, cursor, &layout.bounds(), renderer)
333    }
334
335    fn draw(
336        &self,
337        renderer: &mut crate::Renderer,
338        theme: &crate::Theme,
339        style: &renderer::Style,
340        layout: Layout<'_>,
341        cursor: mouse::Cursor,
342    ) {
343        self._draw(renderer, theme, style, layout, cursor);
344    }
345}
346
347impl<'a, Message: Clone + 'a> crate::widget::Widget<Message, crate::Theme, crate::Renderer>
348    for Overlay<'a, Message>
349{
350    fn size(&self) -> Size<Length> {
351        Size::new(Length::Fixed(self.width), Length::Shrink)
352    }
353
354    fn layout(
355        &mut self,
356        _tree: &mut iced_core::widget::Tree,
357        renderer: &crate::Renderer,
358        limits: &iced::Limits,
359    ) -> layout::Node {
360        let limits = limits.width(self.width);
361
362        self.state
363            .with_data_mut(|tree| self.container.layout(tree, renderer, &limits))
364    }
365
366    fn mouse_interaction(
367        &self,
368        _tree: &Tree,
369        layout: Layout<'_>,
370        cursor: mouse::Cursor,
371        viewport: &Rectangle,
372        renderer: &crate::Renderer,
373    ) -> mouse::Interaction {
374        self._mouse_interaction(layout, cursor, viewport, renderer)
375    }
376
377    fn update(
378        &mut self,
379        _tree: &mut Tree,
380        event: &Event,
381        layout: Layout<'_>,
382        cursor: mouse::Cursor,
383        renderer: &crate::Renderer,
384        clipboard: &mut dyn Clipboard,
385        shell: &mut Shell<'_, Message>,
386        _viewport: &Rectangle,
387    ) {
388        self._update(event, layout, cursor, renderer, clipboard, shell)
389    }
390
391    fn draw(
392        &self,
393        _tree: &Tree,
394        renderer: &mut crate::Renderer,
395        theme: &crate::Theme,
396        style: &renderer::Style,
397        layout: Layout<'_>,
398        cursor: mouse::Cursor,
399        _viewport: &Rectangle,
400    ) {
401        self._draw(renderer, theme, style, layout, cursor);
402    }
403}
404
405impl<'a, Message: Clone + 'a> From<Overlay<'a, Message>> for crate::Element<'a, Message> {
406    fn from(widget: Overlay<'a, Message>) -> Self {
407        Element::new(widget)
408    }
409}
410
411struct List<'a, S: AsRef<str>, Message>
412where
413    [S]: std::borrow::ToOwned,
414{
415    options: Cow<'a, [S]>,
416    icons: Cow<'a, [icon::Handle]>,
417    hovered_option: Arc<Mutex<Option<usize>>>,
418    selected_option: Option<usize>,
419    on_selected: Box<dyn FnMut(usize) -> Message + 'a>,
420    close_on_selected: Option<Message>,
421    on_option_hovered: Option<&'a dyn Fn(usize) -> Message>,
422    padding: Padding,
423    text_size: Option<f32>,
424    text_line_height: text::LineHeight,
425}
426
427impl<S: AsRef<str>, Message> Widget<Message, crate::Theme, crate::Renderer> for List<'_, S, Message>
428where
429    [S]: std::borrow::ToOwned,
430    Message: Clone,
431{
432    fn size(&self) -> Size<Length> {
433        Size::new(Length::Fill, Length::Shrink)
434    }
435
436    fn layout(
437        &mut self,
438        _tree: &mut Tree,
439        renderer: &crate::Renderer,
440        limits: &layout::Limits,
441    ) -> layout::Node {
442        use std::f32;
443
444        let limits = limits.width(Length::Fill).height(Length::Shrink);
445        let text_size = self
446            .text_size
447            .unwrap_or_else(|| text::Renderer::default_size(renderer).0);
448
449        let text_line_height = self.text_line_height.to_absolute(Pixels(text_size));
450
451        let size = {
452            let intrinsic = Size::new(
453                0.0,
454                (f32::from(text_line_height) + self.padding.y()) * self.options.len() as f32,
455            );
456
457            limits.resolve(Length::Fill, Length::Shrink, intrinsic)
458        };
459
460        layout::Node::new(size)
461    }
462
463    fn update(
464        &mut self,
465        _state: &mut Tree,
466        event: &Event,
467        layout: Layout<'_>,
468        cursor: mouse::Cursor,
469        renderer: &crate::Renderer,
470        _clipboard: &mut dyn Clipboard,
471        shell: &mut Shell<'_, Message>,
472        _viewport: &Rectangle,
473    ) {
474        match event {
475            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)) => {
476                let hovered_guard = self.hovered_option.lock().unwrap();
477                if cursor.is_over(layout.bounds())
478                    && let Some(index) = *hovered_guard
479                {
480                    shell.publish((self.on_selected)(index));
481                    if let Some(close_on_selected) = self.close_on_selected.as_ref() {
482                        shell.publish(close_on_selected.clone());
483                    }
484                    shell.capture_event();
485                }
486            }
487            Event::Mouse(mouse::Event::CursorMoved { .. }) => {
488                if let Some(cursor_position) = cursor.position_in(layout.bounds()) {
489                    let text_size = self
490                        .text_size
491                        .unwrap_or_else(|| text::Renderer::default_size(renderer).0);
492
493                    let option_height =
494                        f32::from(self.text_line_height.to_absolute(Pixels(text_size)))
495                            + self.padding.y();
496
497                    let new_hovered_option = (cursor_position.y / option_height) as usize;
498                    let mut hovered_guard = self.hovered_option.lock().unwrap();
499
500                    if *hovered_guard != Some(new_hovered_option) {
501                        shell.request_redraw();
502
503                        if let Some(on_option_hovered) = self.on_option_hovered {
504                            shell.publish(on_option_hovered(new_hovered_option));
505                        }
506                    }
507
508                    *hovered_guard = Some(new_hovered_option);
509                } else {
510                    let mut hovered_guard = self.hovered_option.lock().unwrap();
511
512                    if hovered_guard.is_some() {
513                        *hovered_guard = None;
514                        shell.request_redraw();
515                    }
516                }
517            }
518            Event::Mouse(mouse::Event::CursorLeft) => {
519                let mut hovered_guard = self.hovered_option.lock().unwrap();
520
521                if hovered_guard.is_some() {
522                    *hovered_guard = None;
523                    shell.request_redraw();
524                }
525            }
526            Event::Touch(touch::Event::FingerPressed { .. }) => {
527                if let Some(cursor_position) = cursor.position_in(layout.bounds()) {
528                    let text_size = self
529                        .text_size
530                        .unwrap_or_else(|| text::Renderer::default_size(renderer).0);
531
532                    let option_height =
533                        f32::from(self.text_line_height.to_absolute(Pixels(text_size)))
534                            + self.padding.y();
535                    let mut hovered_guard = self.hovered_option.lock().unwrap();
536
537                    *hovered_guard = Some((cursor_position.y / option_height) as usize);
538
539                    if let Some(index) = *hovered_guard {
540                        shell.publish((self.on_selected)(index));
541                        if let Some(close_on_selected) = self.close_on_selected.as_ref() {
542                            shell.publish(close_on_selected.clone());
543                        }
544                        shell.capture_event();
545                    }
546                }
547            }
548            _ => {}
549        }
550    }
551
552    fn mouse_interaction(
553        &self,
554        _state: &Tree,
555        layout: Layout<'_>,
556        cursor: mouse::Cursor,
557        _viewport: &Rectangle,
558        _renderer: &crate::Renderer,
559    ) -> mouse::Interaction {
560        let is_mouse_over = cursor.is_over(layout.bounds());
561
562        if is_mouse_over {
563            mouse::Interaction::Pointer
564        } else {
565            mouse::Interaction::default()
566        }
567    }
568
569    fn draw(
570        &self,
571        _state: &Tree,
572        renderer: &mut crate::Renderer,
573        theme: &crate::Theme,
574        _style: &renderer::Style,
575        layout: Layout<'_>,
576        _cursor: mouse::Cursor,
577        viewport: &Rectangle,
578    ) {
579        let appearance = theme.appearance(&());
580        let bounds = layout.bounds();
581
582        let text_size = self
583            .text_size
584            .unwrap_or_else(|| text::Renderer::default_size(renderer).0);
585        let option_height =
586            f32::from(self.text_line_height.to_absolute(Pixels(text_size))) + self.padding.y();
587
588        let offset = viewport.y - bounds.y;
589        let start = (offset / option_height) as usize;
590        let end = ((offset + viewport.height) / option_height).ceil() as usize;
591
592        let visible_options = &self.options[start..end.min(self.options.len())];
593
594        for (i, option) in visible_options.iter().enumerate() {
595            let i = start + i;
596
597            let bounds = Rectangle {
598                x: bounds.x,
599                y: option_height.mul_add(i as f32, bounds.y),
600                width: bounds.width,
601                height: option_height,
602            };
603
604            let hovered_guard = self.hovered_option.lock().unwrap();
605
606            let (color, font) = if self.selected_option == Some(i) {
607                let item_x = bounds.x + appearance.border_width;
608                let item_width = appearance.border_width.mul_add(-2.0, bounds.width);
609
610                renderer.fill_quad(
611                    renderer::Quad {
612                        bounds: Rectangle {
613                            x: item_x,
614                            width: item_width,
615                            ..bounds
616                        },
617                        border: Border {
618                            radius: appearance.border_radius,
619                            ..Default::default()
620                        },
621                        shadow: Shadow::default(),
622                        snap: true,
623                    },
624                    appearance.selected_background,
625                );
626
627                let svg_handle =
628                    iced_core::Svg::new(crate::widget::common::object_select().clone())
629                        .color(appearance.selected_text_color)
630                        .border_radius(appearance.border_radius);
631
632                let bounds = Rectangle {
633                    x: item_x + item_width - 16.0 - 8.0,
634                    y: bounds.y + (bounds.height / 2.0 - 8.0),
635                    width: 16.0,
636                    height: 16.0,
637                };
638                svg::Renderer::draw_svg(renderer, svg_handle, bounds, bounds);
639
640                (appearance.selected_text_color, crate::font::semibold())
641            } else if *hovered_guard == Some(i) {
642                let item_x = bounds.x + appearance.border_width;
643                let item_width = appearance.border_width.mul_add(-2.0, bounds.width);
644
645                renderer.fill_quad(
646                    renderer::Quad {
647                        bounds: Rectangle {
648                            x: item_x,
649                            width: item_width,
650                            ..bounds
651                        },
652                        border: Border {
653                            radius: appearance.border_radius,
654                            ..Default::default()
655                        },
656                        shadow: Shadow::default(),
657                        snap: true,
658                    },
659                    appearance.hovered_background,
660                );
661
662                (appearance.hovered_text_color, crate::font::default())
663            } else {
664                (appearance.text_color, crate::font::default())
665            };
666
667            let mut bounds = Rectangle {
668                x: bounds.x + self.padding.left,
669                y: bounds.center_y(),
670                width: f32::INFINITY,
671                ..bounds
672            };
673
674            if let Some(handle) = self.icons.get(i) {
675                let icon_bounds = Rectangle {
676                    x: bounds.x,
677                    y: bounds.y + 8.0 - (bounds.height / 2.0),
678                    width: 20.0,
679                    height: 20.0,
680                };
681
682                bounds.x += 24.0;
683                icon::draw(renderer, handle, icon_bounds);
684            }
685
686            text::Renderer::fill_text(
687                renderer,
688                Text {
689                    content: option.as_ref().to_string(),
690                    bounds: bounds.size(),
691                    size: Pixels(text_size),
692                    line_height: self.text_line_height,
693                    font,
694                    align_x: text::Alignment::Left,
695                    align_y: alignment::Vertical::Center,
696                    shaping: text::Shaping::Advanced,
697                    wrapping: text::Wrapping::default(),
698                    ellipsize: text::Ellipsize::default(),
699                },
700                bounds.position(),
701                color,
702                *viewport,
703            );
704        }
705    }
706}
707
708impl<'a, S: AsRef<str>, Message: 'a> From<List<'a, S, Message>>
709    for Element<'a, Message, crate::Theme, crate::Renderer>
710where
711    [S]: std::borrow::ToOwned,
712    Message: Clone,
713{
714    fn from(list: List<'a, S, Message>) -> Self {
715        Element::new(list)
716    }
717}