Skip to main content

cosmic/widget/dropdown/
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::Id;
6use super::menu::{self, Menu};
7use crate::widget::icon::{self, Handle};
8use crate::{Element, surface};
9use derive_setters::Setters;
10use iced::window;
11use iced_core::event::Event;
12use iced_core::text::{self, Paragraph, Text};
13use iced_core::widget::tree::{self, Tree};
14use iced_core::{
15    Clipboard, Layout, Length, Padding, Pixels, Rectangle, Shadow, Shell, Size, Vector, Widget,
16    alignment, keyboard, layout, mouse, overlay, renderer, svg, touch,
17};
18use iced_widget::pick_list::{self, Catalog};
19use std::borrow::Cow;
20use std::hash::{DefaultHasher, Hash, Hasher};
21use std::sync::atomic::{AtomicBool, Ordering};
22use std::sync::{Arc, LazyLock, Mutex};
23
24pub type DropdownView<Message> = Arc<dyn Fn() -> Element<'static, Message> + Send + Sync>;
25static AUTOSIZE_ID: LazyLock<crate::widget::Id> =
26    LazyLock::new(|| crate::widget::Id::new("cosmic-applet-autosize"));
27
28/// A widget for selecting a single value from a list of selections.
29#[derive(Setters)]
30pub struct Dropdown<'a, S: AsRef<str> + Send + Sync + Clone + 'static, Message, AppMessage>
31where
32    [S]: std::borrow::ToOwned,
33{
34    #[setters(skip)]
35    id: Option<Id>,
36    #[setters(skip)]
37    on_selected: Arc<dyn Fn(usize) -> Message + Send + Sync>,
38    #[setters(skip)]
39    selections: Cow<'a, [S]>,
40    #[setters]
41    icons: Cow<'a, [icon::Handle]>,
42    #[setters(skip)]
43    selected: Option<usize>,
44    #[setters(into)]
45    width: Length,
46    gap: f32,
47    #[setters(into)]
48    padding: Padding,
49    #[setters(strip_option, into)]
50    placeholder: Option<Cow<'a, str>>,
51    #[setters(strip_option)]
52    text_size: Option<f32>,
53    text_line_height: text::LineHeight,
54    #[setters(strip_option)]
55    font: Option<crate::font::Font>,
56    #[setters(skip)]
57    on_surface_action:
58        Option<Arc<dyn Fn(surface::Action<AppMessage>) -> Message + Send + Sync + 'static>>,
59    #[setters(skip)]
60    action_map: Option<Arc<dyn Fn(Message) -> AppMessage + 'static + Send + Sync>>,
61    #[setters(strip_option)]
62    window_id: Option<window::Id>,
63    #[cfg(wayland_platform)]
64    positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
65}
66
67impl<'a, S: AsRef<str> + Send + Sync + Clone + 'static, Message: 'static, AppMessage: 'static>
68    Dropdown<'a, S, Message, AppMessage>
69where
70    [S]: std::borrow::ToOwned,
71{
72    /// The default gap.
73    pub const DEFAULT_GAP: f32 = 4.0;
74
75    /// The default padding.
76    pub const DEFAULT_PADDING: Padding = Padding::new(8.0);
77
78    /// Creates a new [`Dropdown`] with the given list of selections, the current
79    /// selected value, and the message to produce when an option is selected.
80    pub fn new(
81        selections: Cow<'a, [S]>,
82        selected: Option<usize>,
83        on_selected: impl Fn(usize) -> Message + 'static + Send + Sync,
84    ) -> Self {
85        Self {
86            id: None,
87            on_selected: Arc::new(on_selected),
88            selections,
89            icons: Cow::Borrowed(&[]),
90            selected,
91            placeholder: None,
92            width: Length::Shrink,
93            gap: Self::DEFAULT_GAP,
94            padding: Self::DEFAULT_PADDING,
95            text_size: None,
96            text_line_height: text::LineHeight::Relative(1.2),
97            font: None,
98            window_id: None,
99            #[cfg(wayland_platform)]
100            positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner::default(),
101            on_surface_action: None,
102            action_map: None,
103        }
104    }
105
106    #[cfg(wayland_platform)]
107    /// Handle dropdown requests for popup creation.
108    /// Intended to be used with [`crate::app::message::get_popup`]
109    pub fn with_popup<NewAppMessage>(
110        self,
111        parent_id: window::Id,
112        on_surface_action: impl Fn(surface::Action<NewAppMessage>) -> Message + Send + Sync + 'static,
113        action_map: impl Fn(Message) -> NewAppMessage + Send + Sync + 'static,
114    ) -> Dropdown<'a, S, Message, NewAppMessage> {
115        let Self {
116            id,
117            on_selected,
118            selections,
119            icons,
120            selected,
121            placeholder,
122            width,
123            gap,
124            padding,
125            text_size,
126            text_line_height,
127            font,
128            positioner,
129            ..
130        } = self;
131
132        Dropdown::<'a, S, Message, NewAppMessage> {
133            id,
134            on_selected,
135            selections,
136            icons,
137            selected,
138            placeholder,
139            width,
140            gap,
141            padding,
142            text_size,
143            text_line_height,
144            font,
145            on_surface_action: Some(Arc::new(on_surface_action)),
146            action_map: Some(Arc::new(action_map)),
147            window_id: Some(parent_id),
148            positioner,
149        }
150    }
151
152    pub fn id(mut self, id: Id) -> Self {
153        self.id = Some(id);
154        self
155    }
156
157    #[cfg(wayland_platform)]
158    pub fn with_positioner(
159        mut self,
160        positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
161    ) -> Self {
162        self.positioner = positioner;
163        self
164    }
165}
166
167impl<
168    S: AsRef<str> + Send + Sync + Clone + 'static,
169    Message: 'static + Clone,
170    AppMessage: 'static + Clone,
171> Widget<Message, crate::Theme, crate::Renderer> for Dropdown<'_, S, Message, AppMessage>
172where
173    [S]: std::borrow::ToOwned,
174{
175    fn tag(&self) -> tree::Tag {
176        tree::Tag::of::<State>()
177    }
178
179    fn state(&self) -> tree::State {
180        tree::State::new(State::new())
181    }
182
183    fn diff(&mut self, tree: &mut Tree) {
184        let state = tree.state.downcast_mut::<State>();
185
186        let mut selections_changed = state.selections.len() != self.selections.len();
187
188        state
189            .selections
190            .resize_with(self.selections.len(), crate::Plain::default);
191        state.hashes.resize(self.selections.len(), 0);
192
193        for (i, selection) in self.selections.iter().enumerate() {
194            let mut hasher = DefaultHasher::new();
195            selection.as_ref().hash(&mut hasher);
196            let text_hash = hasher.finish();
197
198            if state.hashes[i] == text_hash {
199                continue;
200            }
201
202            selections_changed = true;
203            state.hashes[i] = text_hash;
204            state.selections[i].update(Text {
205                content: selection.as_ref(),
206                bounds: Size::INFINITE,
207                // TODO use the renderer default size
208                size: iced::Pixels(self.text_size.unwrap_or(14.0)),
209                line_height: self.text_line_height,
210                font: self.font.unwrap_or_else(crate::font::default),
211                align_x: text::Alignment::Left,
212                align_y: alignment::Vertical::Top,
213                shaping: text::Shaping::Advanced,
214                wrapping: text::Wrapping::default(),
215                ellipsize: text::Ellipsize::default(),
216            });
217        }
218
219        if state.is_open.load(Ordering::SeqCst) && selections_changed {
220            state.close_operation = true;
221            state.open_operation = true;
222        }
223    }
224
225    fn size(&self) -> Size<Length> {
226        Size::new(self.width, Length::Shrink)
227    }
228
229    fn layout(
230        &mut self,
231        tree: &mut Tree,
232        renderer: &crate::Renderer,
233        limits: &layout::Limits,
234    ) -> layout::Node {
235        layout(
236            renderer,
237            limits,
238            self.width,
239            self.gap,
240            self.padding,
241            self.text_size.unwrap_or(14.0),
242            self.text_line_height,
243            self.font,
244            self.selected.and_then(|id| {
245                self.selections
246                    .get(id)
247                    .map(AsRef::as_ref)
248                    .zip(tree.state.downcast_mut::<State>().selections.get_mut(id))
249            }),
250            self.placeholder.as_deref(),
251            !self.icons.is_empty(),
252        )
253    }
254
255    fn update(
256        &mut self,
257        tree: &mut Tree,
258        event: &Event,
259        layout: Layout<'_>,
260        cursor: mouse::Cursor,
261        _renderer: &crate::Renderer,
262        _clipboard: &mut dyn Clipboard,
263        shell: &mut Shell<'_, Message>,
264        _viewport: &Rectangle,
265    ) {
266        update::<S, Message, AppMessage>(
267            event,
268            layout,
269            cursor,
270            shell,
271            #[cfg(wayland_platform)]
272            self.positioner.clone(),
273            self.on_selected.clone(),
274            self.selected,
275            &self.selections,
276            || tree.state.downcast_mut::<State>(),
277            self.window_id,
278            self.on_surface_action.clone(),
279            self.action_map.clone(),
280            &self.icons,
281            self.gap,
282            self.padding,
283            self.text_size,
284            self.font,
285            self.selected,
286        )
287    }
288
289    fn mouse_interaction(
290        &self,
291        _tree: &Tree,
292        layout: Layout<'_>,
293        cursor: mouse::Cursor,
294        _viewport: &Rectangle,
295        _renderer: &crate::Renderer,
296    ) -> mouse::Interaction {
297        mouse_interaction(layout, cursor)
298    }
299
300    fn draw(
301        &self,
302        tree: &Tree,
303        renderer: &mut crate::Renderer,
304        theme: &crate::Theme,
305        _style: &iced_core::renderer::Style,
306        layout: Layout<'_>,
307        cursor: mouse::Cursor,
308        viewport: &Rectangle,
309    ) {
310        let font = self.font.unwrap_or_else(crate::font::default);
311        draw(
312            renderer,
313            theme,
314            layout,
315            cursor,
316            self.gap,
317            self.padding,
318            self.text_size,
319            self.text_line_height,
320            font,
321            self.selected.and_then(|id| self.selections.get(id)),
322            self.selected.and_then(|id| self.icons.get(id)),
323            self.placeholder.as_deref(),
324            tree.state.downcast_ref::<State>(),
325            viewport,
326        );
327    }
328
329    fn operate(
330        &mut self,
331        _tree: &mut Tree,
332        _layout: Layout<'_>,
333        _renderer: &crate::Renderer,
334        _operation: &mut dyn iced_core::widget::Operation,
335    ) {
336        // TODO: double check operation handling
337        // let state = tree.state.downcast_mut::<State>();
338        // operation.custom(state, self.id.as_ref());
339    }
340
341    fn overlay<'b>(
342        &'b mut self,
343        tree: &'b mut Tree,
344        layout: Layout<'b>,
345        renderer: &crate::Renderer,
346        _viewport: &Rectangle,
347        translation: Vector,
348    ) -> Option<overlay::Element<'b, Message, crate::Theme, crate::Renderer>> {
349        #[cfg(wayland_platform)]
350        if self.window_id.is_some() || self.on_surface_action.is_some() {
351            return None;
352        }
353
354        let state = tree.state.downcast_mut::<State>();
355
356        overlay(
357            layout,
358            renderer,
359            state,
360            self.gap,
361            self.padding,
362            self.text_size.unwrap_or(14.0),
363            self.text_line_height,
364            self.font,
365            &self.selections,
366            &self.icons,
367            self.selected,
368            self.on_selected.as_ref(),
369            translation,
370            None,
371        )
372    }
373
374    // #[cfg(feature = "a11y")]
375    // /// get the a11y nodes for the widget
376    // fn a11y_nodes(
377    //     &self,
378    //     layout: Layout<'_>,
379    //     state: &Tree,
380    //     p: mouse::Cursor,
381    // ) -> iced_accessibility::A11yTree {
382    //     // TODO
383    // }
384}
385
386impl<
387    'a,
388    S: AsRef<str> + Send + Sync + Clone + 'static,
389    Message: 'static + std::clone::Clone,
390    AppMessage: 'static + std::clone::Clone,
391> From<Dropdown<'a, S, Message, AppMessage>> for crate::Element<'a, Message>
392where
393    [S]: std::borrow::ToOwned,
394{
395    fn from(pick_list: Dropdown<'a, S, Message, AppMessage>) -> Self {
396        Self::new(pick_list)
397    }
398}
399
400/// The local state of a [`Dropdown`].
401#[derive(Debug, Clone)]
402pub struct State {
403    icon: Option<svg::Handle>,
404    menu: menu::State,
405    keyboard_modifiers: keyboard::Modifiers,
406    is_open: Arc<AtomicBool>,
407    close_operation: bool,
408    open_operation: bool,
409    hovered_option: Arc<Mutex<Option<usize>>>,
410    hashes: Vec<u64>,
411    selections: Vec<crate::Plain>,
412    popup_id: window::Id,
413}
414
415impl State {
416    /// Creates a new [`State`] for a [`Dropdown`].
417    pub fn new() -> Self {
418        Self {
419            icon: match icon::from_name("pan-down-symbolic").size(16).handle().data {
420                icon::Data::Svg(handle) => Some(handle),
421                icon::Data::Image(_) => None,
422            },
423            menu: menu::State::default(),
424            keyboard_modifiers: keyboard::Modifiers::default(),
425            is_open: Arc::new(AtomicBool::new(false)),
426            hovered_option: Arc::new(Mutex::new(None)),
427            selections: Vec::new(),
428            hashes: Vec::new(),
429            popup_id: window::Id::unique(),
430            close_operation: false,
431            open_operation: false,
432        }
433    }
434}
435
436impl Default for State {
437    fn default() -> Self {
438        Self::new()
439    }
440}
441
442impl super::operation::Dropdown for State {
443    fn close(&mut self) {
444        self.close_operation = true;
445    }
446
447    fn open(&mut self) {
448        self.open_operation = true;
449    }
450}
451
452/// Computes the layout of a [`Dropdown`].
453#[allow(clippy::too_many_arguments)]
454pub fn layout(
455    _renderer: &crate::Renderer,
456    limits: &layout::Limits,
457    width: Length,
458    gap: f32,
459    padding: Padding,
460    text_size: f32,
461    text_line_height: text::LineHeight,
462    font: Option<crate::font::Font>,
463    selection: Option<(&str, &mut crate::Plain)>,
464    placeholder: Option<&str>,
465    has_icons: bool,
466) -> layout::Node {
467    let limits = limits.width(width).height(Length::Shrink).shrink(padding);
468
469    let max_width = match width {
470        Length::Shrink => {
471            let measure = move |(label, paragraph): (_, Option<&mut crate::Plain>)| -> f32 {
472                let paragraph = match paragraph {
473                    Some(p) => {
474                        let text = Text {
475                            content: label,
476                            bounds: Size::new(f32::MAX, f32::MAX),
477                            size: iced::Pixels(text_size),
478                            line_height: text_line_height,
479                            font: font.unwrap_or_else(crate::font::default),
480                            align_x: text::Alignment::Left,
481                            align_y: alignment::Vertical::Top,
482                            shaping: text::Shaping::Advanced,
483                            wrapping: text::Wrapping::default(),
484                            ellipsize: text::Ellipsize::default(),
485                        };
486                        p.update(text);
487                        p
488                    }
489                    None => {
490                        let text = Text {
491                            content: label.to_string(),
492                            bounds: Size::new(f32::MAX, f32::MAX),
493                            size: iced::Pixels(text_size),
494                            line_height: text_line_height,
495                            font: font.unwrap_or_else(crate::font::default),
496                            align_x: text::Alignment::Left,
497                            align_y: alignment::Vertical::Top,
498                            shaping: text::Shaping::Advanced,
499                            wrapping: text::Wrapping::default(),
500                            ellipsize: text::Ellipsize::default(),
501                        };
502                        &mut crate::Plain::new(text)
503                    }
504                };
505                paragraph.min_width().round()
506            };
507
508            selection
509                .map(|(l, p)| (l, Some(p)))
510                .or_else(|| placeholder.map(|l| (l, None)))
511                .map(measure)
512                .unwrap_or_default()
513        }
514        _ => 0.0,
515    };
516
517    let icon_size = if has_icons { 24.0 } else { 0.0 };
518
519    let size = {
520        let intrinsic = Size::new(
521            max_width + icon_size + gap + 16.0,
522            f32::from(text_line_height.to_absolute(Pixels(text_size))),
523        );
524
525        limits
526            .resolve(width, Length::Shrink, intrinsic)
527            .expand(padding)
528    };
529
530    layout::Node::new(size)
531}
532
533/// Processes an [`Event`] and updates the [`State`] of a [`Dropdown`]
534/// accordingly.
535#[allow(clippy::too_many_arguments, clippy::too_many_lines)]
536pub fn update<
537    'a,
538    S: AsRef<str> + Send + Sync + Clone + 'static,
539    Message: Clone + 'static,
540    AppMessage: Clone + 'static,
541>(
542    event: &Event,
543    layout: Layout<'_>,
544    cursor: mouse::Cursor,
545    shell: &mut Shell<'_, Message>,
546    #[cfg(wayland_platform)]
547    _positioner: iced_runtime::platform_specific::wayland::popup::SctkPositioner,
548    on_selected: Arc<dyn Fn(usize) -> Message + Send + Sync + 'static>,
549    selected: Option<usize>,
550    selections: &[S],
551    state: impl FnOnce() -> &'a mut State,
552    _window_id: Option<window::Id>,
553    on_surface_action: Option<
554        Arc<dyn Fn(surface::Action<AppMessage>) -> Message + Send + Sync + 'static>,
555    >,
556    action_map: Option<Arc<dyn Fn(Message) -> AppMessage + Send + Sync + 'static>>,
557    icons: &[icon::Handle],
558    gap: f32,
559    padding: Padding,
560    text_size: Option<f32>,
561    _font: Option<crate::font::Font>,
562    selected_option: Option<usize>,
563) {
564    let state = state();
565
566    let open = |shell: &mut Shell<'_, Message>,
567                state: &mut State,
568                on_selected: Arc<dyn Fn(usize) -> Message + Send + Sync + 'static>| {
569        state.is_open.store(true, Ordering::Relaxed);
570        shell.request_redraw();
571        let mut hovered_guard = state.hovered_option.lock().unwrap();
572        *hovered_guard = selected;
573        let id = window::Id::unique();
574        state.popup_id = id;
575        #[cfg(wayland_platform)]
576        if let Some(((on_surface_action, parent), action_map)) = on_surface_action
577            .as_ref()
578            .zip(_window_id)
579            .zip(action_map.clone())
580        {
581            use iced_runtime::platform_specific::wayland::popup::{
582                SctkPopupSettings, SctkPositioner,
583            };
584
585            use crate::surface::action::LiveSettings;
586            let bounds = layout.bounds();
587            let anchor_rect = Rectangle {
588                x: bounds.x as i32,
589                y: bounds.y as i32,
590                width: bounds.width as i32,
591                height: bounds.height as i32,
592            };
593            let icon_width = if icons.is_empty() { 0.0 } else { 24.0 };
594            let measure = |_label: &str, selection_paragraph: &crate::Paragraph| -> f32 {
595                selection_paragraph.min_width().round()
596            };
597            let pad_width = padding.x().mul_add(2.0, 16.0);
598
599            let selections_width = selections
600                .iter()
601                .zip(state.selections.iter_mut())
602                .map(|(label, selection)| measure(label.as_ref(), selection.raw()))
603                .fold(0.0, |next, current| current.max(next));
604
605            let icons: Cow<'static, [Handle]> = Cow::Owned(icons.to_vec());
606            let selections: Cow<'static, [S]> = Cow::Owned(selections.to_vec());
607            let state = state.clone();
608            let on_close = surface::action::destroy_popup(id);
609            let on_surface_action_clone = on_surface_action.clone();
610            let translation = layout.virtual_offset();
611            let get_popup_action = surface::action::simple_popup::<AppMessage>(
612                LiveSettings::default,
613                move || {
614                    SctkPopupSettings {
615                parent,
616                id,
617                input_zone: None,
618                positioner: SctkPositioner {
619                    size: Some((selections_width as u32 + gap as u32 + pad_width as u32 + icon_width as u32, 10)),
620                    anchor_rect,
621                    // TODO: left or right alignment based on direction?
622                    anchor: cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Anchor::BottomLeft,
623                    gravity: cctk::wayland_protocols::xdg::shell::client::xdg_positioner::Gravity::BottomRight,
624                    reactive: true,
625                    offset: ((-padding.left - translation.x) as i32, -translation.y as i32),
626                    constraint_adjustment: 9,
627                    ..Default::default()
628                },
629                parent_size: None,
630                grab: false,
631                close_with_children: true,
632            }
633                },
634                Some(Box::new(move || {
635                    let action_map = action_map.clone();
636                    let on_selected = on_selected.clone();
637                    let e: Element<'static, crate::Action<AppMessage>> =
638                        Element::from(menu_widget(
639                            bounds,
640                            &state,
641                            gap,
642                            padding,
643                            text_size.unwrap_or(14.0),
644                            selections.clone(),
645                            icons.clone(),
646                            selected_option,
647                            Arc::new(move |i| on_selected.clone()(i)),
648                            Some(on_surface_action_clone(on_close.clone())),
649                        ))
650                        .map(move |m| crate::Action::App(action_map.clone()(m)));
651                    e
652                })),
653            );
654            shell.publish(on_surface_action(get_popup_action));
655        }
656    };
657
658    let is_open = state.is_open.load(Ordering::Relaxed);
659    let refresh = state.close_operation && state.open_operation;
660
661    if state.close_operation {
662        state.close_operation = false;
663        state.is_open.store(false, Ordering::SeqCst);
664        if is_open {
665            shell.request_redraw();
666            #[cfg(wayland_platform)]
667            if let Some(ref on_close) = on_surface_action {
668                shell.publish(on_close(surface::action::destroy_popup(state.popup_id)));
669            }
670        }
671    }
672
673    if state.open_operation {
674        state.open_operation = false;
675        state.is_open.store(true, Ordering::SeqCst);
676        if (refresh && is_open) || (!refresh && !is_open) {
677            open(shell, state, on_selected.clone());
678        }
679    }
680
681    match event {
682        Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
683        | Event::Touch(touch::Event::FingerPressed { .. }) => {
684            let is_open = state.is_open.load(Ordering::Relaxed);
685            if is_open {
686                // Event wasn't processed by overlay, so cursor was clicked either outside it's
687                // bounds or on the drop-down, either way we close the overlay.
688                state.is_open.store(false, Ordering::Relaxed);
689                shell.request_redraw();
690                #[cfg(wayland_platform)]
691                if let Some(on_close) = on_surface_action {
692                    shell.publish(on_close(surface::action::destroy_popup(state.popup_id)));
693                }
694                shell.capture_event();
695            } else if cursor.is_over(layout.bounds()) {
696                open(shell, state, on_selected);
697                shell.capture_event();
698            }
699        }
700        Event::Mouse(mouse::Event::WheelScrolled {
701            delta: mouse::ScrollDelta::Lines { .. },
702        }) => {
703            let is_open = state.is_open.load(Ordering::Relaxed);
704
705            if state.keyboard_modifiers.command() && cursor.is_over(layout.bounds()) && !is_open {
706                let next_index = selected.map(|index| index + 1).unwrap_or_default();
707
708                if selections.len() < next_index {
709                    shell.publish((on_selected)(next_index));
710                }
711
712                shell.capture_event();
713            }
714        }
715        Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
716            state.keyboard_modifiers = *modifiers;
717        }
718        Event::Keyboard(keyboard::Event::KeyPressed {
719            key: keyboard::Key::Named(keyboard::key::Named::Escape),
720            ..
721        }) => {
722            let is_open = state.is_open.load(Ordering::Relaxed);
723            if is_open {
724                state.is_open.store(false, Ordering::Relaxed);
725                shell.request_redraw();
726                #[cfg(wayland_platform)]
727                if let Some(on_close) = on_surface_action {
728                    shell.publish(on_close(surface::action::destroy_popup(state.popup_id)));
729                }
730                shell.capture_event();
731            }
732        }
733
734        _ => {}
735    }
736}
737
738/// Returns the current [`mouse::Interaction`] of a [`Dropdown`].
739#[must_use]
740pub fn mouse_interaction(layout: Layout<'_>, cursor: mouse::Cursor) -> mouse::Interaction {
741    let bounds = layout.bounds();
742    let is_mouse_over = cursor.is_over(bounds);
743
744    if is_mouse_over {
745        mouse::Interaction::Pointer
746    } else {
747        mouse::Interaction::default()
748    }
749}
750
751#[cfg(wayland_platform)]
752/// Returns the current menu widget of a [`Dropdown`].
753#[allow(clippy::too_many_arguments)]
754pub fn menu_widget<
755    S: AsRef<str> + Send + Sync + Clone + 'static,
756    Message: 'static + std::clone::Clone,
757>(
758    bounds: Rectangle,
759    state: &State,
760    gap: f32,
761    padding: Padding,
762    text_size: f32,
763    selections: Cow<'static, [S]>,
764    icons: Cow<'static, [icon::Handle]>,
765    selected_option: Option<usize>,
766    on_selected: Arc<dyn Fn(usize) -> Message + Send + Sync + 'static>,
767    close_on_selected: Option<Message>,
768) -> crate::Element<'static, Message>
769where
770    [S]: std::borrow::ToOwned,
771{
772    let icon_width = if icons.is_empty() { 0.0 } else { 24.0 };
773    let measure = |_label: &str, selection_paragraph: &crate::Paragraph| -> f32 {
774        selection_paragraph.min_width().round()
775    };
776    let selections_width = selections
777        .iter()
778        .zip(state.selections.iter())
779        .map(|(label, selection)| measure(label.as_ref(), selection.raw()))
780        .fold(0.0, |next, current| current.max(next));
781    let pad_width = padding.x().mul_add(2.0, 16.0);
782
783    let width = selections_width + gap + pad_width + icon_width;
784    let is_open = state.is_open.clone();
785    let menu: Menu<'static, S, Message> = Menu::new(
786        state.menu.clone(),
787        selections,
788        icons,
789        state.hovered_option.clone(),
790        selected_option,
791        move |option| {
792            is_open.store(false, Ordering::Relaxed);
793
794            (on_selected)(option)
795        },
796        None,
797        close_on_selected,
798    )
799    .width(width)
800    .padding(padding)
801    .text_size(text_size);
802
803    crate::widget::autosize::autosize(
804        menu.popup(iced::Point::new(0., 0.), bounds.height),
805        AUTOSIZE_ID.clone(),
806    )
807    .auto_height(true)
808    .auto_width(true)
809    .min_height(1.)
810    .min_width(width)
811    .into()
812}
813
814/// Returns the current overlay of a [`Dropdown`].
815#[allow(clippy::too_many_arguments)]
816pub fn overlay<'a, S: AsRef<str> + Send + Sync + Clone + 'static, Message: std::clone::Clone + 'a>(
817    layout: Layout<'_>,
818    _renderer: &crate::Renderer,
819    state: &'a mut State,
820    gap: f32,
821    padding: Padding,
822    text_size: f32,
823    _text_line_height: text::LineHeight,
824    _font: Option<crate::font::Font>,
825    selections: &'a [S],
826    icons: &'a [icon::Handle],
827    selected_option: Option<usize>,
828    on_selected: &'a dyn Fn(usize) -> Message,
829    translation: Vector,
830    close_on_selected: Option<Message>,
831) -> Option<overlay::Element<'a, Message, crate::Theme, crate::Renderer>>
832where
833    [S]: std::borrow::ToOwned,
834{
835    if state.is_open.load(Ordering::Relaxed) {
836        let bounds = layout.bounds();
837
838        let menu = Menu::new(
839            state.menu.clone(),
840            Cow::Borrowed(selections),
841            Cow::Borrowed(icons),
842            state.hovered_option.clone(),
843            selected_option,
844            |option| {
845                state.is_open.store(false, Ordering::Relaxed);
846
847                (on_selected)(option)
848            },
849            None,
850            close_on_selected,
851        )
852        .width({
853            let measure = |_label: &str, selection_paragraph: &crate::Paragraph| -> f32 {
854                selection_paragraph.min_width().round()
855            };
856
857            let pad_width = padding.x().mul_add(2.0, 16.0);
858
859            let icon_width = if icons.is_empty() { 0.0 } else { 24.0 };
860
861            selections
862                .iter()
863                .zip(state.selections.iter_mut())
864                .map(|(label, selection)| measure(label.as_ref(), selection.raw()))
865                .fold(0.0, |next, current| current.max(next))
866                + gap
867                + pad_width
868                + icon_width
869        })
870        .padding(padding)
871        .text_size(text_size);
872
873        let mut position = layout.position();
874        position.x -= padding.left;
875        position.x += translation.x;
876        position.y += translation.y;
877        Some(menu.overlay(position, bounds.height))
878    } else {
879        None
880    }
881}
882
883/// Draws a [`Dropdown`].
884#[allow(clippy::too_many_arguments)]
885pub fn draw<'a, S>(
886    renderer: &mut crate::Renderer,
887    theme: &crate::Theme,
888    layout: Layout<'_>,
889    cursor: mouse::Cursor,
890    gap: f32,
891    padding: Padding,
892    text_size: Option<f32>,
893    text_line_height: text::LineHeight,
894    font: crate::font::Font,
895    selected: Option<&'a S>,
896    icon: Option<&'a icon::Handle>,
897    placeholder: Option<&'a str>,
898    state: &'a State,
899    viewport: &Rectangle,
900) where
901    S: AsRef<str> + 'a,
902{
903    let bounds = layout.bounds();
904    let is_mouse_over = cursor.is_over(bounds);
905
906    let style = if is_mouse_over {
907        theme.style(&(), pick_list::Status::Hovered)
908    } else {
909        theme.style(&(), pick_list::Status::Active)
910    };
911
912    iced_core::Renderer::fill_quad(
913        renderer,
914        renderer::Quad {
915            bounds,
916            border: style.border,
917            shadow: Shadow::default(),
918            snap: true,
919        },
920        style.background,
921    );
922
923    if let Some(handle) = state.icon.clone() {
924        let svg_handle = svg::Svg::new(handle).color(style.text_color);
925        let bounds = Rectangle {
926            x: bounds.x + bounds.width - gap - 16.0,
927            y: bounds.center_y() - 8.0,
928            width: 16.0,
929            height: 16.0,
930        };
931        svg::Renderer::draw_svg(renderer, svg_handle, bounds, bounds);
932    }
933
934    if let Some(content) = selected.map(AsRef::as_ref).or(placeholder) {
935        let text_size = text_size.unwrap_or_else(|| text::Renderer::default_size(renderer).0);
936
937        let mut bounds = Rectangle {
938            x: bounds.x + padding.left,
939            y: bounds.center_y(),
940            width: bounds.width - padding.x(),
941            height: f32::from(text_line_height.to_absolute(Pixels(text_size))),
942        };
943
944        if let Some(handle) = icon {
945            let icon_bounds = Rectangle {
946                x: bounds.x,
947                y: bounds.y - (bounds.height / 2.0) - 2.0,
948                width: 20.0,
949                height: 20.0,
950            };
951
952            bounds.x += 24.0;
953            icon::draw(renderer, handle, icon_bounds);
954        }
955
956        text::Renderer::fill_text(
957            renderer,
958            Text {
959                content: content.to_string(),
960                size: iced::Pixels(text_size),
961                line_height: text_line_height,
962                font,
963                bounds: bounds.size(),
964                align_x: text::Alignment::Left,
965                align_y: alignment::Vertical::Center,
966                shaping: text::Shaping::Advanced,
967                wrapping: text::Wrapping::default(),
968                ellipsize: text::Ellipsize::default(),
969            },
970            bounds.position(),
971            style.text_color,
972            *viewport,
973        );
974    }
975}