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