Skip to main content

cosmic/widget/dropdown/multi/
widget.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
5use super::menu::{self, Menu};
6use crate::widget::icon;
7use derive_setters::Setters;
8use iced_core::event::Event;
9use iced_core::text::{self, Text};
10use iced_core::widget::tree::{self, Tree};
11use iced_core::{
12    Clipboard, Layout, Length, Padding, Pixels, Rectangle, Shadow, Shell, Size, Vector, Widget,
13    alignment, keyboard, layout, mouse, overlay, renderer, svg, touch,
14};
15use iced_widget::pick_list;
16
17pub use iced_widget::pick_list::{Catalog, Style};
18
19/// A widget for selecting a single value from a list of selections.
20#[derive(Setters)]
21pub struct Dropdown<'a, S: AsRef<str>, Message, Item> {
22    #[setters(skip)]
23    on_selected: Box<dyn Fn(Item) -> Message + 'a>,
24    #[setters(skip)]
25    selections: &'a super::Model<S, Item>,
26    #[setters(into)]
27    width: Length,
28    gap: f32,
29    #[setters(into)]
30    padding: Padding,
31    #[setters(strip_option)]
32    text_size: Option<f32>,
33    text_line_height: text::LineHeight,
34    #[setters(strip_option)]
35    font: Option<crate::font::Font>,
36}
37
38impl<'a, S: AsRef<str>, Message, Item: Clone + PartialEq + 'static> Dropdown<'a, S, Message, Item> {
39    /// The default gap.
40    pub const DEFAULT_GAP: f32 = 4.0;
41
42    /// The default padding.
43    pub const DEFAULT_PADDING: Padding = Padding::new(8.0);
44
45    /// Creates a new [`Dropdown`] with the given list of selections, the current
46    /// selected value, and the message to produce when an option is selected.
47    pub fn new(
48        selections: &'a super::Model<S, Item>,
49        on_selected: impl Fn(Item) -> Message + 'a,
50    ) -> Self {
51        Self {
52            on_selected: Box::new(on_selected),
53            selections,
54            width: Length::Shrink,
55            gap: Self::DEFAULT_GAP,
56            padding: Self::DEFAULT_PADDING,
57            text_size: None,
58            text_line_height: text::LineHeight::Relative(1.2),
59            font: None,
60        }
61    }
62}
63
64impl<'a, S: AsRef<str>, Message: 'a, Item: Clone + PartialEq + 'static>
65    Widget<Message, crate::Theme, crate::Renderer> for Dropdown<'a, S, Message, Item>
66{
67    fn tag(&self) -> tree::Tag {
68        tree::Tag::of::<State<Item>>()
69    }
70
71    fn state(&self) -> tree::State {
72        tree::State::new(State::<Item>::new())
73    }
74
75    fn size(&self) -> Size<Length> {
76        Size::new(self.width, Length::Shrink)
77    }
78
79    fn layout(
80        &mut self,
81        tree: &mut Tree,
82        renderer: &crate::Renderer,
83        limits: &layout::Limits,
84    ) -> layout::Node {
85        layout(
86            renderer,
87            limits,
88            self.width,
89            self.gap,
90            self.padding,
91            self.text_size.unwrap_or(14.0),
92            self.text_line_height,
93            self.font,
94            self.selections.selected.as_ref().and_then(|id| {
95                self.selections.get(id).map(AsRef::as_ref).zip({
96                    let state = tree.state.downcast_mut::<State<Item>>();
97
98                    if state.selections.is_empty() {
99                        for list in &self.selections.lists {
100                            for (_, item) in &list.options {
101                                state
102                                    .selections
103                                    .push((item.clone(), crate::Plain::default()));
104                            }
105                        }
106                    }
107
108                    state
109                        .selections
110                        .iter_mut()
111                        .find(|(i, _)| i == id)
112                        .map(|(_, p)| p)
113                })
114            }),
115        )
116    }
117
118    fn update(
119        &mut self,
120        tree: &mut Tree,
121        event: &Event,
122        layout: Layout<'_>,
123        cursor: mouse::Cursor,
124        _renderer: &crate::Renderer,
125        _clipboard: &mut dyn Clipboard,
126        shell: &mut Shell<'_, Message>,
127        _viewport: &Rectangle,
128    ) {
129        update(
130            event,
131            layout,
132            cursor,
133            shell,
134            self.on_selected.as_ref(),
135            self.selections,
136            || tree.state.downcast_mut::<State<Item>>(),
137        );
138    }
139
140    fn mouse_interaction(
141        &self,
142        _tree: &Tree,
143        layout: Layout<'_>,
144        cursor: mouse::Cursor,
145        _viewport: &Rectangle,
146        _renderer: &crate::Renderer,
147    ) -> mouse::Interaction {
148        mouse_interaction(layout, cursor)
149    }
150
151    fn draw(
152        &self,
153        tree: &Tree,
154        renderer: &mut crate::Renderer,
155        theme: &crate::Theme,
156        _style: &iced_core::renderer::Style,
157        layout: Layout<'_>,
158        cursor: mouse::Cursor,
159        viewport: &Rectangle,
160    ) {
161        let font = self.font.unwrap_or_else(crate::font::default);
162
163        draw(
164            renderer,
165            theme,
166            layout,
167            cursor,
168            self.gap,
169            self.padding,
170            self.text_size,
171            self.text_line_height,
172            font,
173            self.selections
174                .selected
175                .as_ref()
176                .and_then(|id| self.selections.get(id)),
177            tree.state.downcast_ref::<State<Item>>(),
178            viewport,
179        );
180    }
181
182    fn overlay<'b>(
183        &'b mut self,
184        tree: &'b mut Tree,
185        layout: Layout<'b>,
186        renderer: &crate::Renderer,
187        _viewport: &Rectangle,
188        translation: Vector,
189    ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
190        let state = tree.state.downcast_mut::<State<Item>>();
191
192        overlay(
193            layout,
194            renderer,
195            state,
196            self.gap,
197            self.padding,
198            self.text_size.unwrap_or(14.0),
199            self.font,
200            self.text_line_height,
201            self.selections,
202            &self.on_selected,
203            translation,
204        )
205    }
206}
207
208impl<'a, S: AsRef<str>, Message: 'a, Item: Clone + PartialEq + 'static>
209    From<Dropdown<'a, S, Message, Item>> for crate::Element<'a, Message>
210{
211    fn from(pick_list: Dropdown<'a, S, Message, Item>) -> Self {
212        Self::new(pick_list)
213    }
214}
215
216/// The local state of a [`Dropdown`].
217#[derive(Debug)]
218pub struct State<Item: Clone + PartialEq + 'static> {
219    icon: Option<svg::Handle>,
220    menu: menu::State,
221    keyboard_modifiers: keyboard::Modifiers,
222    is_open: bool,
223    hovered_option: Option<Item>,
224    selections: Vec<(Item, crate::Plain)>,
225    descriptions: Vec<crate::Plain>,
226}
227
228impl<Item: Clone + PartialEq + 'static> State<Item> {
229    /// Creates a new [`State`] for a [`Dropdown`].
230    pub fn new() -> Self {
231        Self {
232            icon: match icon::from_name("pan-down-symbolic").size(16).handle().data {
233                icon::Data::Svg(handle) => Some(handle),
234                icon::Data::Image(_) => None,
235            },
236            menu: menu::State::default(),
237            keyboard_modifiers: keyboard::Modifiers::default(),
238            is_open: false,
239            hovered_option: None,
240            selections: Vec::new(),
241            descriptions: Vec::new(),
242        }
243    }
244}
245
246impl<Item: Clone + PartialEq + 'static> Default for State<Item> {
247    fn default() -> Self {
248        Self::new()
249    }
250}
251
252/// Computes the layout of a [`Dropdown`].
253#[allow(clippy::too_many_arguments)]
254pub fn layout(
255    _renderer: &crate::Renderer,
256    limits: &layout::Limits,
257    width: Length,
258    gap: f32,
259    padding: Padding,
260    text_size: f32,
261    text_line_height: text::LineHeight,
262    font: Option<crate::font::Font>,
263    selection: Option<(&str, &mut crate::Plain)>,
264) -> layout::Node {
265    let limits = limits.width(width).height(Length::Shrink).shrink(padding);
266
267    let max_width = match width {
268        Length::Shrink => {
269            let measure = move |(label, paragraph): (_, &mut crate::Plain)| -> f32 {
270                paragraph.update(Text {
271                    content: label,
272                    bounds: Size::new(f32::MAX, f32::MAX),
273                    size: iced::Pixels(text_size),
274                    line_height: text_line_height,
275                    font: font.unwrap_or_else(crate::font::default),
276                    align_x: text::Alignment::Left,
277                    align_y: alignment::Vertical::Top,
278                    shaping: text::Shaping::Advanced,
279                    wrapping: text::Wrapping::default(),
280                    ellipsize: text::Ellipsize::default(),
281                });
282                paragraph.min_width().round()
283            };
284
285            selection.map(measure).unwrap_or_default()
286        }
287        _ => 0.0,
288    };
289
290    let size = {
291        let intrinsic = Size::new(
292            max_width + gap + 16.0,
293            f32::from(text_line_height.to_absolute(Pixels(text_size))),
294        );
295
296        limits
297            .resolve(width, Length::Shrink, intrinsic)
298            .expand(padding)
299    };
300
301    layout::Node::new(size)
302}
303
304/// Processes an [`Event`] and updates the [`State`] of a [`Dropdown`]
305/// accordingly.
306#[allow(clippy::too_many_arguments)]
307pub fn update<'a, S: AsRef<str>, Message, Item: Clone + PartialEq + 'static + 'a>(
308    event: &Event,
309    layout: Layout<'_>,
310    cursor: mouse::Cursor,
311    shell: &mut Shell<'_, Message>,
312    on_selected: &dyn Fn(Item) -> Message,
313    selections: &super::Model<S, Item>,
314    state: impl FnOnce() -> &'a mut State<Item>,
315) {
316    match event {
317        Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
318        | Event::Touch(touch::Event::FingerPressed { .. }) => {
319            let state = state();
320
321            if state.is_open {
322                // Event wasn't processed by overlay, so cursor was clicked either outside it's
323                // bounds or on the drop-down, either way we close the overlay.
324                state.is_open = false;
325
326                shell.capture_event();
327            } else if cursor.is_over(layout.bounds()) {
328                state.is_open = true;
329                state.hovered_option = selections.selected.clone();
330
331                shell.capture_event();
332            }
333        }
334        Event::Mouse(mouse::Event::WheelScrolled {
335            delta: mouse::ScrollDelta::Lines { .. },
336        }) => {
337            let state = state();
338
339            if state.keyboard_modifiers.command()
340                && cursor.is_over(layout.bounds())
341                && !state.is_open
342            {
343                if let Some(option) = selections.next() {
344                    shell.publish((on_selected)(option.1.clone()));
345                }
346
347                shell.capture_event();
348            }
349        }
350        Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
351            let state = state();
352
353            state.keyboard_modifiers = *modifiers;
354        }
355        _ => {}
356    }
357}
358
359/// Returns the current [`mouse::Interaction`] of a [`Dropdown`].
360#[must_use]
361pub fn mouse_interaction(layout: Layout<'_>, cursor: mouse::Cursor) -> mouse::Interaction {
362    let bounds = layout.bounds();
363    let is_mouse_over = cursor.is_over(bounds);
364
365    if is_mouse_over {
366        mouse::Interaction::Pointer
367    } else {
368        mouse::Interaction::default()
369    }
370}
371
372/// Returns the current overlay of a [`Dropdown`].
373#[allow(clippy::too_many_arguments)]
374pub fn overlay<'a, S: AsRef<str>, Message: 'a, Item: Clone + PartialEq + 'static>(
375    layout: Layout<'_>,
376    _renderer: &crate::Renderer,
377    state: &'a mut State<Item>,
378    gap: f32,
379    padding: Padding,
380    text_size: f32,
381    font: Option<crate::font::Font>,
382    text_line_height: text::LineHeight,
383    selections: &'a super::Model<S, Item>,
384    on_selected: &'a dyn Fn(Item) -> Message,
385    translation: Vector,
386) -> Option<overlay::Element<'a, Message, crate::Theme, crate::Renderer>> {
387    if state.is_open {
388        let description_line_height = text::LineHeight::Absolute(Pixels(
389            text_line_height.to_absolute(Pixels(text_size)).0 + 4.0,
390        ));
391
392        let bounds = layout.bounds();
393
394        let menu = Menu::new(
395            &mut state.menu,
396            selections,
397            &mut state.hovered_option,
398            selections.selected.as_ref(),
399            |option| {
400                state.is_open = false;
401
402                (on_selected)(option)
403            },
404            None,
405        )
406        .width({
407            let measure =
408                |label: &str, paragraph: &mut crate::Plain, line_height: text::LineHeight| {
409                    paragraph.update(Text {
410                        content: label,
411                        bounds: Size::new(f32::MAX, f32::MAX),
412                        size: iced::Pixels(text_size),
413                        line_height,
414                        font: font.unwrap_or_else(crate::font::default),
415                        align_x: text::Alignment::Left,
416                        align_y: alignment::Vertical::Top,
417                        shaping: text::Shaping::Advanced,
418                        wrapping: text::Wrapping::default(),
419                        ellipsize: text::Ellipsize::default(),
420                    });
421                    paragraph.min_width().round()
422                };
423
424            let mut desc_count = 0;
425            padding.x().mul_add(
426                2.0,
427                selections
428                    .elements()
429                    .map(|element| match element {
430                        super::menu::OptionElement::Description(desc) => {
431                            let paragraph = if state.descriptions.len() > desc_count {
432                                &mut state.descriptions[desc_count]
433                            } else {
434                                state.descriptions.push(crate::Plain::default());
435                                state.descriptions.last_mut().unwrap()
436                            };
437                            desc_count += 1;
438                            measure(desc.as_ref(), paragraph, description_line_height)
439                        }
440
441                        super::menu::OptionElement::Option((option, item)) => {
442                            let selection_index =
443                                state.selections.iter().position(|(i, _)| i == item);
444
445                            let selection_index = match selection_index {
446                                Some(index) => index,
447                                None => {
448                                    state
449                                        .selections
450                                        .push((item.clone(), crate::Plain::default()));
451                                    state.selections.len() - 1
452                                }
453                            };
454
455                            let paragraph = &mut state.selections[selection_index].1;
456
457                            measure(option.as_ref(), paragraph, text_line_height)
458                        }
459
460                        super::menu::OptionElement::Separator => 1.0,
461                    })
462                    .fold(0.0, |next, current| current.max(next)),
463            ) + gap
464                + 16.0
465        })
466        .padding(padding)
467        .text_size(text_size);
468
469        let mut position = layout.position();
470        position.x -= padding.left;
471        position.x += translation.x;
472        position.y += translation.y;
473        Some(menu.overlay(position, bounds.height))
474    } else {
475        None
476    }
477}
478
479/// Draws a [`Dropdown`].
480#[allow(clippy::too_many_arguments)]
481pub fn draw<'a, S, Item: Clone + PartialEq + 'static>(
482    renderer: &mut crate::Renderer,
483    theme: &crate::Theme,
484    layout: Layout<'_>,
485    cursor: mouse::Cursor,
486    gap: f32,
487    padding: Padding,
488    text_size: Option<f32>,
489    text_line_height: text::LineHeight,
490    font: crate::font::Font,
491    selected: Option<&'a S>,
492    state: &'a State<Item>,
493    viewport: &Rectangle,
494) where
495    S: AsRef<str> + 'a,
496{
497    let bounds = layout.bounds();
498    let is_mouse_over = cursor.is_over(bounds);
499
500    let style = if is_mouse_over {
501        theme.style(&(), pick_list::Status::Hovered)
502    } else {
503        theme.style(&(), pick_list::Status::Active)
504    };
505
506    iced_core::Renderer::fill_quad(
507        renderer,
508        renderer::Quad {
509            bounds,
510            border: style.border,
511            shadow: Shadow::default(),
512            snap: true,
513        },
514        style.background,
515    );
516
517    if let Some(handle) = state.icon.as_ref() {
518        let svg_handle = iced_core::Svg::new(handle.clone()).color(style.text_color);
519        let svg_bounds = Rectangle {
520            x: bounds.x + bounds.width - gap - 16.0,
521            y: bounds.center_y() - 8.0,
522            width: 16.0,
523            height: 16.0,
524        };
525        svg::Renderer::draw_svg(renderer, svg_handle, svg_bounds, svg_bounds);
526    }
527
528    if let Some(content) = selected.map(AsRef::as_ref) {
529        let text_size = text_size.unwrap_or_else(|| text::Renderer::default_size(renderer).0);
530
531        let bounds = Rectangle {
532            x: bounds.x + padding.left,
533            y: bounds.center_y(),
534            width: bounds.width - padding.x(),
535            height: f32::from(text_line_height.to_absolute(Pixels(text_size))),
536        };
537
538        text::Renderer::fill_text(
539            renderer,
540            Text {
541                content: content.to_string(),
542                size: iced::Pixels(text_size),
543                line_height: text_line_height,
544                font,
545                bounds: bounds.size(),
546                align_x: text::Alignment::Left,
547                align_y: alignment::Vertical::Center,
548                shaping: text::Shaping::Advanced,
549                wrapping: text::Wrapping::default(),
550                ellipsize: text::Ellipsize::default(),
551            },
552            bounds.position(),
553            style.text_color,
554            *viewport,
555        );
556    }
557}