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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
//     https://www.apache.org/licenses/LICENSE-2.0

//! Combobox

use super::{menu::MenuEntry, Column, Mark, PopupFrame, StringLabel};
use kas::event::{Command, Scroll, ScrollDelta};
use kas::prelude::*;
use kas::theme::{MarkStyle, TextClass};
use kas::WindowId;
use std::fmt::Debug;
use std::rc::Rc;

#[derive(Clone, Debug)]
struct IndexMsg(usize);

impl_scope! {
    /// A pop-up multiple choice menu
    ///
    /// # Messages
    ///
    /// A combobox presents a menu with a fixed set of choices when clicked.
    /// Each choice has an associated "message" value of type `M`.
    ///
    /// If no selection handler exists, then the choice's message is emitted
    /// when selected. If a handler is specified via [`Self::on_select`], then
    /// this message is passed to the handler and not emitted.
    #[autoimpl(Debug ignore self.on_select)]
    #[impl_default]
    #[derive(Clone)]
    #[widget {
        layout = button 'frame: row: [self.label, self.mark];
        navigable = true;
        hover_highlight = true;
    }]
    pub struct ComboBox<M: Clone + Debug + 'static> {
        core: widget_core!(),
        #[widget]
        label: StringLabel,
        #[widget]
        mark: Mark = Mark::new(MarkStyle::Point(Direction::Down)),
        #[widget]
        popup: ComboPopup<M>,
        active: usize,
        opening: bool,
        popup_id: Option<WindowId>,
        on_select: Option<Rc<dyn Fn(&mut EventMgr, M)>>,
    }

    impl Widget for Self {
        fn pre_configure(&mut self, mgr: &mut ConfigMgr, id: WidgetId) {
            self.core.id = id;
            mgr.new_accel_layer(self.id(), true);
        }

        fn nav_next(&mut self, _: &mut ConfigMgr, _: bool, _: Option<usize>) -> Option<usize> {
            // We have no child within our rect
            None
        }

        fn handle_event(&mut self, mgr: &mut EventMgr, event: Event) -> Response {
            let open_popup = |s: &mut Self, mgr: &mut EventMgr, key_focus: bool| {
                s.popup_id = mgr.add_popup(kas::Popup {
                    id: s.popup.id(),
                    parent: s.id(),
                    direction: Direction::Down,
                });
                if let Some(w) = s.popup.inner.inner.get_child_mut(s.active) {
                    mgr.next_nav_focus(w, false, key_focus);
                }
            };

            match event {
                Event::Command(cmd) => {
                    if let Some(popup_id) = self.popup_id {
                        let next = |mgr: &mut EventMgr, s, clr, rev| {
                            if clr {
                                mgr.clear_nav_focus();
                            }
                            mgr.next_nav_focus(s, rev, true);
                        };
                        match cmd {
                            cmd if cmd.is_activate() => mgr.close_window(popup_id, true),
                            Command::Up => next(mgr, self, false, true),
                            Command::Down => next(mgr, self, false, false),
                            Command::Home => next(mgr, self, true, false),
                            Command::End => next(mgr, self, true, true),
                            _ => return Response::Unused,
                        }
                    } else {
                        let last = self.len().saturating_sub(1);
                        match cmd {
                            cmd if cmd.is_activate() => open_popup(self, mgr, true),
                            Command::Up => *mgr |= self.set_active(self.active.saturating_sub(1)),
                            Command::Down => *mgr |= self.set_active((self.active + 1).min(last)),
                            Command::Home => *mgr |= self.set_active(0),
                            Command::End => *mgr |= self.set_active(last),
                            _ => return Response::Unused,
                        }
                    }
                    Response::Used
                }
                Event::Scroll(ScrollDelta::LineDelta(_, y)) if self.popup_id.is_none() => {
                    if y > 0.0 {
                        *mgr |= self.set_active(self.active.saturating_sub(1));
                    } else if y < 0.0 {
                        let last = self.len().saturating_sub(1);
                        *mgr |= self.set_active((self.active + 1).min(last));
                    }
                    Response::Used
                }
                Event::PressStart {
                    source,
                    start_id,
                    coord,
                } => {
                    if start_id.as_ref().map(|id| self.is_ancestor_of(id)).unwrap_or(false) {
                        if source.is_primary() {
                            mgr.grab_press_unique(self.id(), source, coord, None);
                            mgr.set_grab_depress(source, start_id);
                            self.opening = self.popup_id.is_none();
                        }
                        Response::Used
                    } else {
                        if let Some(id) = self.popup_id {
                            mgr.close_window(id, false);
                        }
                        Response::Unused
                    }
                }
                Event::PressMove {
                    source,
                    cur_id,
                    coord,
                    ..
                } => {
                    if self.popup_id.is_none() {
                        open_popup(self, mgr, false);
                    }
                    let cond = self.popup.inner.rect().contains(coord);
                    let target = if cond { cur_id } else { None };
                    mgr.set_grab_depress(source, target.clone());
                    if let Some(id) = target {
                        mgr.set_nav_focus(id, false);
                    }
                    Response::Used
                }
                Event::PressEnd { end_id, success, .. } if success => {
                    if let Some(id) = end_id {
                        if self.eq_id(&id) {
                            if self.opening {
                                if self.popup_id.is_none() {
                                    open_popup(self, mgr, false);
                                }
                                return Response::Used;
                            }
                        } else if self.popup_id.is_some() && self.popup.is_ancestor_of(&id) {
                            return mgr.send(self, id, Event::Command(Command::Activate));
                        }
                    }
                    if let Some(id) = self.popup_id {
                        mgr.close_window(id, true);
                    }
                    Response::Used
                }
                Event::PressEnd { .. } =>Response::Used,
                Event::PopupRemoved(id) => {
                    debug_assert_eq!(Some(id), self.popup_id);
                    self.popup_id = None;
                    Response::Used
                }
                _ => Response::Unused,
            }
        }

        fn handle_message(&mut self, mgr: &mut EventMgr, _: usize) {
            if let Some(IndexMsg(index)) = mgr.try_pop_msg() {
                *mgr |= self.set_active(index);
                if let Some(id) = self.popup_id {
                    mgr.close_window(id, true);
                }
                if let Some(ref f) = self.on_select {
                    if let Some(msg) = mgr.try_pop_msg() {
                        (f)(mgr, msg);
                    }
                }
            }
        }

        fn handle_scroll(&mut self, mgr: &mut EventMgr, _: Scroll) {
            mgr.set_scroll(Scroll::None);
        }
    }
}

impl<M, T, I> From<I> for ComboBox<M>
where
    M: Clone + Debug + 'static,
    T: Into<AccelString>,
    I: IntoIterator<Item = (T, M)>,
{
    /// Construct a combobox
    ///
    /// Constructs a combobox with labels derived from an iterator over string
    /// types. For example:
    /// ```
    /// # use kas_widgets::ComboBox;
    /// let combobox = ComboBox::from([("zero", 0), ("one", 1), ("two", 2)]);
    /// ```
    ///
    /// Initially, the first entry is active.
    #[inline]
    fn from(iter: I) -> Self {
        let entries = iter
            .into_iter()
            .map(|(label, msg)| MenuEntry::new(label, msg))
            .collect();
        Self::new_vec(entries)
    }
}

impl<M: Clone + Debug + 'static> ComboBox<M> {
    /// Construct an empty combobox
    #[inline]
    pub fn new() -> Self {
        Self::default()
    }

    /// Construct a combobox with the given menu entries
    ///
    /// A combobox presents a menu with a fixed set of choices when clicked.
    ///
    /// Initially, the first entry is active.
    #[inline]
    pub fn new_vec(entries: Vec<MenuEntry<M>>) -> Self {
        let label = entries.get(0).map(|entry| entry.get_string());
        let label = StringLabel::new(label.unwrap_or_default()).with_class(TextClass::Button);
        ComboBox {
            label,
            popup: ComboPopup {
                core: Default::default(),
                inner: PopupFrame::new(
                    Column::new_vec(entries).on_message(|mgr, index| mgr.push_msg(IndexMsg(index))),
                ),
            },
            ..Default::default()
        }
    }

    /// Set the selection handler `f`
    ///
    /// On selection of a new choice the closure `f` is called with the choice's
    /// message.
    #[inline]
    #[must_use]
    pub fn on_select<F>(self, f: F) -> ComboBox<M>
    where
        F: Fn(&mut EventMgr, M) + 'static,
    {
        ComboBox {
            core: self.core,
            label: self.label,
            mark: self.mark,
            popup: self.popup,
            active: self.active,
            opening: self.opening,
            popup_id: self.popup_id,
            on_select: Some(Rc::new(f)),
        }
    }
}

impl<M: Clone + Debug + 'static> ComboBox<M> {
    /// Get the index of the active choice
    ///
    /// This index is normally less than the number of choices (`self.len()`),
    /// but may not be if set programmatically or there are no choices.
    #[inline]
    pub fn active(&self) -> usize {
        self.active
    }

    /// Set the active choice (inline style)
    #[inline]
    pub fn with_active(mut self, index: usize) -> Self {
        let _ = self.set_active(index);
        self
    }

    /// Set the active choice
    pub fn set_active(&mut self, index: usize) -> TkAction {
        if self.active != index && index < self.popup.inner.len() {
            self.active = index;
            let string = if index < self.len() {
                self.popup.inner[index].get_string()
            } else {
                "".to_string()
            };
            self.label.set_string(string)
        } else {
            TkAction::empty()
        }
    }

    /// Get the number of entries
    #[inline]
    pub fn len(&self) -> usize {
        self.popup.inner.len()
    }

    /// True if the box contains no entries
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.popup.inner.is_empty()
    }

    /// Remove all choices
    pub fn clear(&mut self) {
        self.popup.inner.clear()
    }

    /// Add a choice to the combobox, in last position
    ///
    /// Returns the index of the new choice
    //
    // TODO(opt): these methods cause full-window resize. They don't need to
    // resize at all if the menu is closed!
    pub fn push<T: Into<AccelString>>(&mut self, mgr: &mut ConfigMgr, label: T, msg: M) -> usize {
        let column = &mut self.popup.inner;
        column.push(mgr, MenuEntry::new(label, msg))
    }

    /// Pops the last choice from the combobox
    pub fn pop(&mut self, mgr: &mut ConfigMgr) -> Option<()> {
        self.popup.inner.pop(mgr).map(|_| ())
    }

    /// Add a choice at position `index`
    ///
    /// Panics if `index > len`.
    pub fn insert<T: Into<AccelString>>(
        &mut self,
        mgr: &mut ConfigMgr,
        index: usize,
        label: T,
        msg: M,
    ) {
        let column = &mut self.popup.inner;
        column.insert(mgr, index, MenuEntry::new(label, msg));
    }

    /// Removes the choice at position `index`
    ///
    /// Panics if `index` is out of bounds.
    pub fn remove(&mut self, mgr: &mut ConfigMgr, index: usize) {
        self.popup.inner.remove(mgr, index);
    }

    /// Replace the choice at `index`
    ///
    /// Panics if `index` is out of bounds.
    pub fn replace<T: Into<AccelString>>(
        &mut self,
        mgr: &mut ConfigMgr,
        index: usize,
        label: T,
        msg: M,
    ) {
        self.popup
            .inner
            .replace(mgr, index, MenuEntry::new(label, msg));
    }
}

impl_scope! {
    #[autoimpl(Default)]
    #[derive(Clone, Debug)]
    #[widget{
        layout = self.inner;
    }]
    struct ComboPopup<M: Clone + Debug + 'static> {
        core: widget_core!(),
        #[widget]
        inner: PopupFrame<Column<MenuEntry<M>>>,
    }
}