1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
// Copyright 2023 System76 <info@system76.com>
// Copyright 2019 Héctor Ramón, Iced contributors
// SPDX-License-Identifier: MPL-2.0 AND MIT

use super::menu::{self, Menu};
use crate::widget::icon;
use derive_setters::Setters;
use iced::Radians;
use iced_core::event::{self, Event};
use iced_core::text::{self, Paragraph, Text};
use iced_core::widget::tree::{self, Tree};
use iced_core::{alignment, keyboard, layout, mouse, overlay, renderer, svg, touch, Shadow};
use iced_core::{
    Clipboard, Layout, Length, Padding, Pixels, Rectangle, Shell, Size, Vector, Widget,
};
use iced_widget::pick_list::{self, Catalog};
use std::ffi::OsStr;
use std::hash::{DefaultHasher, Hash, Hasher};

/// A widget for selecting a single value from a list of selections.
#[derive(Setters)]
pub struct Dropdown<'a, S: AsRef<str>, Message> {
    #[setters(skip)]
    on_selected: Box<dyn Fn(usize) -> Message + 'a>,
    #[setters(skip)]
    selections: &'a [S],
    #[setters]
    icons: &'a [icon::Handle],
    #[setters(skip)]
    selected: Option<usize>,
    #[setters(into)]
    width: Length,
    gap: f32,
    #[setters(into)]
    padding: Padding,
    #[setters(strip_option)]
    text_size: Option<f32>,
    text_line_height: text::LineHeight,
    #[setters(strip_option)]
    font: Option<crate::font::Font>,
}

impl<'a, S: AsRef<str>, Message> Dropdown<'a, S, Message> {
    /// The default gap.
    pub const DEFAULT_GAP: f32 = 4.0;

    /// The default padding.
    pub const DEFAULT_PADDING: Padding = Padding::new(8.0);

    /// Creates a new [`Dropdown`] with the given list of selections, the current
    /// selected value, and the message to produce when an option is selected.
    pub fn new(
        selections: &'a [S],
        selected: Option<usize>,
        on_selected: impl Fn(usize) -> Message + 'a,
    ) -> Self {
        Self {
            on_selected: Box::new(on_selected),
            selections,
            icons: &[],
            selected,
            width: Length::Shrink,
            gap: Self::DEFAULT_GAP,
            padding: Self::DEFAULT_PADDING,
            text_size: None,
            text_line_height: text::LineHeight::Relative(1.2),
            font: None,
        }
    }
}

impl<'a, S: AsRef<str>, Message: 'a> Widget<Message, crate::Theme, crate::Renderer>
    for Dropdown<'a, S, Message>
{
    fn tag(&self) -> tree::Tag {
        tree::Tag::of::<State>()
    }

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

    fn diff(&mut self, tree: &mut Tree) {
        let state = tree.state.downcast_mut::<State>();

        state
            .selections
            .resize_with(self.selections.len(), crate::Plain::default);
        state.hashes.resize(self.selections.len(), 0);

        for (i, selection) in self.selections.iter().enumerate() {
            let mut hasher = DefaultHasher::new();
            selection.as_ref().hash(&mut hasher);
            let text_hash = hasher.finish();

            if state.hashes[i] == text_hash {
                continue;
            }

            state.hashes[i] = text_hash;
            state.selections[i].update(Text {
                content: selection.as_ref(),
                bounds: Size::INFINITY,
                // TODO use the renderer default size
                size: iced::Pixels(self.text_size.unwrap_or(14.0)),
                line_height: self.text_line_height,
                font: self.font.unwrap_or_else(crate::font::default),
                horizontal_alignment: alignment::Horizontal::Left,
                vertical_alignment: alignment::Vertical::Top,
                shaping: text::Shaping::Advanced,
                wrapping: text::Wrapping::default(),
            });
        }
    }

    fn size(&self) -> Size<Length> {
        Size::new(self.width, Length::Shrink)
    }

    fn layout(
        &self,
        tree: &mut Tree,
        renderer: &crate::Renderer,
        limits: &layout::Limits,
    ) -> layout::Node {
        layout(
            renderer,
            limits,
            self.width,
            self.gap,
            self.padding,
            self.text_size.unwrap_or(14.0),
            self.text_line_height,
            self.font,
            self.selected.and_then(|id| {
                self.selections
                    .get(id)
                    .map(AsRef::as_ref)
                    .zip(tree.state.downcast_mut::<State>().selections.get_mut(id))
            }),
            !self.icons.is_empty(),
        )
    }

    fn on_event(
        &mut self,
        tree: &mut Tree,
        event: Event,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _renderer: &crate::Renderer,
        _clipboard: &mut dyn Clipboard,
        shell: &mut Shell<'_, Message>,
        _viewport: &Rectangle,
    ) -> event::Status {
        update(
            &event,
            layout,
            cursor,
            shell,
            self.on_selected.as_ref(),
            self.selected,
            self.selections,
            || tree.state.downcast_mut::<State>(),
        )
    }

    fn mouse_interaction(
        &self,
        _tree: &Tree,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        _viewport: &Rectangle,
        _renderer: &crate::Renderer,
    ) -> mouse::Interaction {
        mouse_interaction(layout, cursor)
    }

    fn draw(
        &self,
        tree: &Tree,
        renderer: &mut crate::Renderer,
        theme: &crate::Theme,
        _style: &iced_core::renderer::Style,
        layout: Layout<'_>,
        cursor: mouse::Cursor,
        viewport: &Rectangle,
    ) {
        let font = self.font.unwrap_or_else(|| crate::font::default());
        draw(
            renderer,
            theme,
            layout,
            cursor,
            self.gap,
            self.padding,
            self.text_size,
            self.text_line_height,
            font,
            self.selected.and_then(|id| self.selections.get(id)),
            self.selected.and_then(|id| self.icons.get(id)),
            tree.state.downcast_ref::<State>(),
            viewport,
        );
    }

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

        overlay(
            layout,
            renderer,
            state,
            self.gap,
            self.padding,
            self.text_size.unwrap_or(14.0),
            self.text_line_height,
            self.font,
            self.selections,
            self.icons,
            self.selected,
            &self.on_selected,
            translation,
        )
    }

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

impl<'a, S: AsRef<str>, Message: 'a> From<Dropdown<'a, S, Message>>
    for crate::Element<'a, Message>
{
    fn from(pick_list: Dropdown<'a, S, Message>) -> Self {
        Self::new(pick_list)
    }
}

/// The local state of a [`Dropdown`].
#[derive(Debug)]
pub struct State {
    icon: Option<svg::Handle>,
    menu: menu::State,
    keyboard_modifiers: keyboard::Modifiers,
    is_open: bool,
    hovered_option: Option<usize>,
    hashes: Vec<u64>,
    selections: Vec<crate::Plain>,
}

impl State {
    /// Creates a new [`State`] for a [`Dropdown`].
    pub fn new() -> Self {
        Self {
            icon: match icon::from_name("pan-down-symbolic").size(16).handle().data {
                icon::Data::Name(named) => named
                    .path()
                    .filter(|path| path.extension().is_some_and(|ext| ext == OsStr::new("svg")))
                    .map(iced_core::svg::Handle::from_path),
                icon::Data::Svg(handle) => Some(handle),
                icon::Data::Image(_) => None,
            },
            menu: menu::State::default(),
            keyboard_modifiers: keyboard::Modifiers::default(),
            is_open: false,
            hovered_option: None,
            selections: Vec::new(),
            hashes: Vec::new(),
        }
    }
}

impl Default for State {
    fn default() -> Self {
        Self::new()
    }
}

/// Computes the layout of a [`Dropdown`].
#[allow(clippy::too_many_arguments)]
pub fn layout(
    renderer: &crate::Renderer,
    limits: &layout::Limits,
    width: Length,
    gap: f32,
    padding: Padding,
    text_size: f32,
    text_line_height: text::LineHeight,
    font: Option<crate::font::Font>,
    selection: Option<(&str, &mut crate::Plain)>,
    has_icons: bool,
) -> layout::Node {
    use std::f32;

    let limits = limits.width(width).height(Length::Shrink).shrink(padding);

    let max_width = match width {
        Length::Shrink => {
            let measure = move |(label, paragraph): (_, &mut crate::Plain)| -> f32 {
                paragraph.update(Text {
                    content: label,
                    bounds: Size::new(f32::MAX, f32::MAX),
                    size: iced::Pixels(text_size),
                    line_height: text_line_height,
                    font: font.unwrap_or_else(|| crate::font::default()),
                    horizontal_alignment: alignment::Horizontal::Left,
                    vertical_alignment: alignment::Vertical::Top,
                    shaping: text::Shaping::Advanced,
                    wrapping: text::Wrapping::default(),
                });
                paragraph.min_width().round()
            };

            selection.map(measure).unwrap_or_default()
        }
        _ => 0.0,
    };

    let icon_size = if has_icons { 24.0 } else { 0.0 };

    let size = {
        let intrinsic = Size::new(
            max_width + icon_size + gap + 16.0,
            f32::from(text_line_height.to_absolute(Pixels(text_size))),
        );

        limits
            .resolve(width, Length::Shrink, intrinsic)
            .expand(padding)
    };

    layout::Node::new(size)
}

/// Processes an [`Event`] and updates the [`State`] of a [`Dropdown`]
/// accordingly.
#[allow(clippy::too_many_arguments)]
pub fn update<'a, S: AsRef<str>, Message>(
    event: &Event,
    layout: Layout<'_>,
    cursor: mouse::Cursor,
    shell: &mut Shell<'_, Message>,
    on_selected: &dyn Fn(usize) -> Message,
    selected: Option<usize>,
    selections: &[S],
    state: impl FnOnce() -> &'a mut State,
) -> event::Status {
    match event {
        Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
        | Event::Touch(touch::Event::FingerPressed { .. }) => {
            let state = state();

            if state.is_open {
                // Event wasn't processed by overlay, so cursor was clicked either outside it's
                // bounds or on the drop-down, either way we close the overlay.
                state.is_open = false;

                event::Status::Captured
            } else if cursor.is_over(layout.bounds()) {
                state.is_open = true;
                state.hovered_option = selected;

                event::Status::Captured
            } else {
                event::Status::Ignored
            }
        }
        Event::Mouse(mouse::Event::WheelScrolled {
            delta: mouse::ScrollDelta::Lines { .. },
        }) => {
            let state = state();

            if state.keyboard_modifiers.command()
                && cursor.is_over(layout.bounds())
                && !state.is_open
            {
                let next_index = selected.map(|index| index + 1).unwrap_or_default();

                if selections.len() < next_index {
                    shell.publish((on_selected)(next_index));
                }

                event::Status::Captured
            } else {
                event::Status::Ignored
            }
        }
        Event::Keyboard(keyboard::Event::ModifiersChanged(modifiers)) => {
            let state = state();

            state.keyboard_modifiers = *modifiers;

            event::Status::Ignored
        }
        _ => event::Status::Ignored,
    }
}

/// Returns the current [`mouse::Interaction`] of a [`Dropdown`].
#[must_use]
pub fn mouse_interaction(layout: Layout<'_>, cursor: mouse::Cursor) -> mouse::Interaction {
    let bounds = layout.bounds();
    let is_mouse_over = cursor.is_over(bounds);

    if is_mouse_over {
        mouse::Interaction::Pointer
    } else {
        mouse::Interaction::default()
    }
}

/// Returns the current overlay of a [`Dropdown`].
#[allow(clippy::too_many_arguments)]
pub fn overlay<'a, S: AsRef<str>, Message: 'a>(
    layout: Layout<'_>,
    _renderer: &crate::Renderer,
    state: &'a mut State,
    gap: f32,
    padding: Padding,
    text_size: f32,
    _text_line_height: text::LineHeight,
    _font: Option<crate::font::Font>,
    selections: &'a [S],
    icons: &'a [icon::Handle],
    selected_option: Option<usize>,
    on_selected: &'a dyn Fn(usize) -> Message,
    translation: Vector,
) -> Option<overlay::Element<'a, Message, crate::Theme, crate::Renderer>> {
    if state.is_open {
        let bounds = layout.bounds();

        let menu = Menu::new(
            &mut state.menu,
            selections,
            icons,
            &mut state.hovered_option,
            selected_option,
            |option| {
                state.is_open = false;

                (on_selected)(option)
            },
            None,
        )
        .width({
            let measure = |_label: &str, selection_paragraph: &crate::Paragraph| -> f32 {
                selection_paragraph.min_width().round()
            };

            let pad_width = padding.horizontal().mul_add(2.0, 16.0);

            let icon_width = if icons.is_empty() { 0.0 } else { 24.0 };

            selections
                .iter()
                .zip(state.selections.iter_mut())
                .map(|(label, selection)| measure(label.as_ref(), selection.raw()))
                .fold(0.0, |next, current| current.max(next))
                + gap
                + pad_width
                + icon_width
        })
        .padding(padding)
        .text_size(text_size);

        let mut position = layout.position();
        position.x -= padding.left;
        position.x += translation.x;
        position.y += translation.y;
        Some(menu.overlay(position, bounds.height))
    } else {
        None
    }
}

/// Draws a [`Dropdown`].
#[allow(clippy::too_many_arguments)]
pub fn draw<'a, S>(
    renderer: &mut crate::Renderer,
    theme: &crate::Theme,
    layout: Layout<'_>,
    cursor: mouse::Cursor,
    gap: f32,
    padding: Padding,
    text_size: Option<f32>,
    text_line_height: text::LineHeight,
    font: crate::font::Font,
    selected: Option<&'a S>,
    icon: Option<&'a icon::Handle>,
    state: &'a State,
    viewport: &Rectangle,
) where
    S: AsRef<str> + 'a,
{
    let bounds = layout.bounds();
    let is_mouse_over = cursor.is_over(bounds);

    let style = if is_mouse_over {
        theme.style(&(), pick_list::Status::Hovered)
    } else {
        theme.style(&(), pick_list::Status::Active)
    };

    iced_core::Renderer::fill_quad(
        renderer,
        renderer::Quad {
            bounds,
            border: style.border,
            shadow: Shadow::default(),
        },
        style.background,
    );

    if let Some(handle) = state.icon.clone() {
        let svg_handle = svg::Svg::new(handle).color(style.text_color);

        svg::Renderer::draw_svg(
            renderer,
            svg_handle,
            Rectangle {
                x: bounds.x + bounds.width - gap - 16.0,
                y: bounds.center_y() - 8.0,
                width: 16.0,
                height: 16.0,
            },
        );
    }

    if let Some(content) = selected.map(AsRef::as_ref) {
        let text_size = text_size.unwrap_or_else(|| text::Renderer::default_size(renderer).0);

        let mut bounds = Rectangle {
            x: bounds.x + padding.left,
            y: bounds.center_y(),
            width: bounds.width - padding.horizontal(),
            height: f32::from(text_line_height.to_absolute(Pixels(text_size))),
        };

        if let Some(handle) = icon {
            let icon_bounds = Rectangle {
                x: bounds.x,
                y: bounds.y - (bounds.height / 2.0) - 2.0,
                width: 20.0,
                height: 20.0,
            };

            bounds.x += 24.0;
            icon::draw(renderer, handle, icon_bounds);
        }

        text::Renderer::fill_text(
            renderer,
            Text {
                content: content.to_string(),
                size: iced::Pixels(text_size),
                line_height: text_line_height,
                font,
                bounds: bounds.size(),
                horizontal_alignment: alignment::Horizontal::Left,
                vertical_alignment: alignment::Vertical::Center,
                shaping: text::Shaping::Advanced,
                wrapping: text::Wrapping::default(),
            },
            bounds.position(),
            style.text_color,
            *viewport,
        );
    }
}