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

use ::{
    Button,
    ButtonStyle,
    Canvas,
    CharacterCache,
    Color,
    Colorable,
    Element,
    FontSize,
    Frameable,
    GlyphCache,
    Labelable,
    NodeIndex,
    Positionable,
    Rect,
    Scalar,
    Sizeable,
    Theme,
};
use widget::{self, Widget};


/// The index of a selected item.
pub type Idx = usize;
/// The number of items in a list.
pub type Len = usize;

/// Displays a given `Vec<String>` as a selectable drop down menu. It's reaction is triggered upon
/// selection of a list item.
pub struct DropDownList<'a, F> {
    common: widget::CommonBuilder,
    strings: &'a mut Vec<String>,
    selected: &'a mut Option<Idx>,
    maybe_react: Option<F>,
    maybe_label: Option<&'a str>,
    style: Style,
    enabled: bool,
}

/// Styling for the DropDownList, necessary for constructing its renderable Element.
#[allow(missing_copy_implementations)]
#[derive(PartialEq, Clone, Debug, RustcEncodable, RustcDecodable)]
pub struct Style {
    /// Color of the widget.
    pub maybe_color: Option<Color>,
    /// Width of the widget's frame.
    pub maybe_frame: Option<f64>,
    /// Color of the widget's frame.
    pub maybe_frame_color: Option<Color>,
    /// Color of the item labels.
    pub maybe_label_color: Option<Color>,
    /// Font size for the item labels.
    pub maybe_label_font_size: Option<u32>,
    /// Maximum height of the Open menu before the scrollbar appears.
    pub maybe_max_visible_height: Option<MaxHeight>,
}

/// Represents the state of the DropDownList.
#[derive(PartialEq, Clone, Debug)]
pub struct State {
    menu_state: MenuState,
    maybe_label: Option<String>,
    buttons: Vec<(NodeIndex, String)>,
    maybe_selected: Option<Idx>,
    maybe_canvas_idx: Option<NodeIndex>,
}

/// Representations of the max height of the visible area of the DropDownList.
#[derive(PartialEq, Clone, Copy, Debug, RustcEncodable, RustcDecodable)]
pub enum MaxHeight {
    Items(usize),
    Scalar(f64),
}

/// Whether the DropDownList is currently open or closed.
#[derive(PartialEq, Clone, Copy, Debug)]
pub enum MenuState {
    Closed,
    Open,
}

impl<'a, F> DropDownList<'a, F> {

    /// Construct a new DropDownList.
    pub fn new(strings: &'a mut Vec<String>, selected: &'a mut Option<Idx>) -> DropDownList<'a, F> {
        DropDownList {
            common: widget::CommonBuilder::new(),
            strings: strings,
            selected: selected,
            maybe_react: None,
            maybe_label: None,
            enabled: true,
            style: Style::new(),
        }
    }

    /// Set the DropDownList's reaction. It will be triggered upon selection of a list item.
    pub fn react(mut self, reaction: F) -> DropDownList<'a, F> {
        self.maybe_react = Some(reaction);
        self
    }

    /// If true, will allow user inputs.  If false, will disallow user inputs.
    pub fn enabled(mut self, flag: bool) -> Self {
        self.enabled = flag;
        self
    }

    /// Set the maximum height of the DropDownList (before the scrollbar appears) as a number of
    /// items.
    pub fn max_visible_items(mut self, num: usize) -> Self {
        self.style.maybe_max_visible_height = Some(MaxHeight::Items(num));
        self
    }

    /// Set the maximum height of the DropDownList (before the scrollbar appears) as a scalar
    /// height.
    pub fn max_visible_height(mut self, height: f64) -> Self {
        self.style.maybe_max_visible_height = Some(MaxHeight::Scalar(height));
        self
    }

}


impl<'a, F> Widget for DropDownList<'a, F> where
    F: FnMut(&mut Option<Idx>, Idx, &str),
{
    type State = State;
    type Style = Style;
    fn common(&self) -> &widget::CommonBuilder { &self.common }
    fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common }
    fn unique_kind(&self) -> &'static str { "DropDownList" }
    fn init_state(&self) -> State {
        State {
            menu_state: MenuState::Closed,
            buttons: Vec::new(),
            maybe_label: None,
            maybe_selected: None,
            maybe_canvas_idx: None,
        }
    }
    fn style(&self) -> Style { self.style.clone() }

    fn default_width<C: CharacterCache>(&self, theme: &Theme, _: &GlyphCache<C>) -> Scalar {
        const DEFAULT_WIDTH: Scalar = 128.0;
        self.common.maybe_width.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.common.maybe_width.unwrap_or(DEFAULT_WIDTH)
        })).unwrap_or(DEFAULT_WIDTH)
    }

    fn default_height(&self, theme: &Theme) -> Scalar {
        const DEFAULT_HEIGHT: Scalar = 32.0;
        self.common.maybe_height.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.common.maybe_height.unwrap_or(DEFAULT_HEIGHT)
        })).unwrap_or(DEFAULT_HEIGHT)
    }

    /// Update the state of the DropDownList.
    fn update<C>(mut self, args: widget::UpdateArgs<Self, C>) -> Option<State>
        where C: CharacterCache,
    {
        use std::borrow::Cow;

        let widget::UpdateArgs { idx, prev_state, rect, style, mut ui } = args;
        let widget::State { ref state, .. } = *prev_state;
        let (global_mouse, window_dim) = {
            let input = ui.input();
            (input.global_mouse, input.window_dim)
        };
        let frame = style.frame(ui.theme());
        let num_strings = self.strings.len();
        let mut buttons = Cow::Borrowed(&state.buttons[..]);
        let canvas_idx = state.maybe_canvas_idx.unwrap_or_else(|| ui.new_unique_node_index());

        // Check that the selected index, if given, is not greater than the number of strings.
        let selected = self.selected.and_then(|idx| if idx < num_strings { Some(idx) }
                                                    else { None });

        // If the number of buttons that we have in our previous state doesn't match the number of
        // strings we've just been given, we need to resize our buttons Vec.
        if buttons.len() < num_strings {
            let num_buttons = buttons.len();
            buttons.to_mut().extend((num_buttons..num_strings).map(|i| {
                (ui.new_unique_node_index(), self.strings[i].to_owned())
            }));
        }

        // Determine the new menu state by checking whether or not any of our Button's reactions
        // are triggered.
        let new_menu_state = match state.menu_state {

            // If closed, we only want the button at the selected index to be drawn.
            MenuState::Closed => {

                // Get the button index and the label for the closed menu's button.
                let (button_idx, label) = selected
                    .map(|i| (buttons[i].0, &self.strings[i][..]))
                    .unwrap_or_else(|| (buttons[0].0, self.maybe_label.unwrap_or("")));

                // Use the pre-existing button widget to act as our button.
                let mut was_clicked = false;
                {
                    let mut button = Button::new()
                        .point(rect.xy())
                        .dim(rect.dim())
                        .label(label)
                        .parent(Some(idx))
                        .react(|| was_clicked = true);
                    let is_selected = false;
                    button.style = style.button_style(is_selected);
                    button.set(button_idx, &mut ui);
                }

                // If the closed menu was clicked, we want to open it.
                if was_clicked { MenuState::Open } else { MenuState::Closed }
            },

            // Otherwise if open, we want to set all the buttons that would be currently visible.
            MenuState::Open => {

                let (xy, dim) = rect.xy_dim();
                let max_visible_height = {
                    let bottom_win_y = (-window_dim[1]) / 2.0;
                    const WINDOW_PADDING: Scalar = 20.0;
                    let max = xy[1] + dim[1] / 2.0 - bottom_win_y - WINDOW_PADDING;
                    style.max_visible_height(ui.theme()).map(|max_height| {
                        let height = match max_height {
                            MaxHeight::Items(num) => (dim[1] - frame) * num as Scalar + frame,
                            MaxHeight::Scalar(height) => height,
                        };
                        ::utils::partial_min(height, max)
                    }).unwrap_or(max)
                };
                let canvas_dim = [dim[0], max_visible_height];
                let canvas_shift_y = ::position::align_top_of(dim[1], canvas_dim[1]);
                let canvas_xy = [xy[0], xy[1] + canvas_shift_y];
                let canvas_rect = Rect::from_xy_dim(canvas_xy, canvas_dim);
                Canvas::new()
                    .color(::color::black().alpha(0.0))
                    .frame_color(::color::black().alpha(0.0))
                    .dim([dim[0], max_visible_height])
                    .point(canvas_xy)
                    .parent(Some(idx))
                    .floating(true)
                    .vertical_scrolling(true)
                    .set(canvas_idx, &mut ui);

                let labels = self.strings.iter();
                let button_indices = state.buttons.iter().map(|&(idx, _)| idx);
                let xys = (0..num_strings).map(|i| [xy[0], xy[1] - i as f64 * (dim[1] - frame)]);
                let iter = labels.zip(button_indices).zip(xys).enumerate();
                let mut was_clicked = None;
                for (i, ((label, button_node_idx), button_xy)) in iter {
                    let mut button = Button::new()
                        .dim(dim)
                        .label(label)
                        .parent(Some(canvas_idx))
                        .point(button_xy)
                        .react(|| was_clicked = Some(i));
                    button.style = style.button_style(Some(i) == selected);
                    button.set(button_node_idx, &mut ui);
                }

                // If one of the buttons was clicked, we want to close the menu.
                if let Some(i) = was_clicked {

                    // If we were given some react function, we'll call it.
                    if let Some(ref mut react) = self.maybe_react {
                        *self.selected = selected;
                        react(self.selected, i, &self.strings[i])
                    }

                    MenuState::Closed
                // Otherwise if the mouse was released somewhere else we should close the menu.
                } else if global_mouse.left.was_just_pressed
                && !canvas_rect.is_over(global_mouse.xy) {
                    MenuState::Closed
                } else {
                    MenuState::Open
                }
            },

        };

        // Function for constructing a new DropDownList State.
        let new_state = |buttons: Cow<[(NodeIndex, String)]>| {
            State {
                menu_state: new_menu_state,
                maybe_label: self.maybe_label.as_ref().map(|label| label.to_string()),
                buttons: buttons.into_owned(),
                maybe_selected: *self.selected,
                maybe_canvas_idx: Some(canvas_idx),
            }
        };

        // Check whether or not the state has changed since the previous update.
        let state_has_changed = state.menu_state != new_menu_state
            || &state.buttons[..] != &buttons[..]
            || state.maybe_selected != *self.selected
            || state.maybe_label.as_ref().map(|string| &string[..]) != self.maybe_label
            || state.maybe_canvas_idx != Some(canvas_idx);

        // Construct the new state if there was a change.
        if state_has_changed { Some(new_state(buttons)) } else { None }
    }

    /// Construct an Element from the given DropDownList State.
    fn draw<C>(_args: widget::DrawArgs<Self, C>) -> Element
        where C: CharacterCache,
    {
        // We don't need to draw anything, as DropDownList is entirely composed of other widgets.
        ::elmesque::element::empty()
    }

}


impl Style {

    /// Construct the default Style.
    pub fn new() -> Style {
        Style {
            maybe_color: None,
            maybe_frame: None,
            maybe_frame_color: None,
            maybe_label_color: None,
            maybe_label_font_size: None,
            maybe_max_visible_height: None,
        }
    }

    /// Get the Color for an Element.
    pub fn color(&self, theme: &Theme) -> Color {
        self.maybe_color.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.style.maybe_color.unwrap_or(theme.shape_color)
        })).unwrap_or(theme.shape_color)
    }

    /// Get the frame for an Element.
    pub fn frame(&self, theme: &Theme) -> f64 {
        self.maybe_frame.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.style.maybe_frame.unwrap_or(theme.frame_width)
        })).unwrap_or(theme.frame_width)
    }

    /// Get the frame Color for an Element.
    pub fn frame_color(&self, theme: &Theme) -> Color {
        self.maybe_frame_color.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.style.maybe_frame_color.unwrap_or(theme.frame_color)
        })).unwrap_or(theme.frame_color)
    }

    /// Get the label Color for an Element.
    pub fn label_color(&self, theme: &Theme) -> Color {
        self.maybe_label_color.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.style.maybe_label_color.unwrap_or(theme.label_color)
        })).unwrap_or(theme.label_color)
    }

    /// Get the label font size for an Element.
    pub fn label_font_size(&self, theme: &Theme) -> FontSize {
        self.maybe_label_font_size.or(theme.maybe_drop_down_list.as_ref().map(|default| {
            default.style.maybe_label_font_size.unwrap_or(theme.font_size_medium)
        })).unwrap_or(theme.font_size_medium)
    }

    /// Get the maximum visible height of the DropDownList.
    pub fn max_visible_height(&self, theme: &Theme) -> Option<MaxHeight> {
        if let Some(height) = self.maybe_max_visible_height { Some(height) }
        else if let Some(Some(height)) = theme.maybe_drop_down_list.as_ref()
            .map(|default| default.style.maybe_max_visible_height) { Some(height) }
        else { None }
    }

    /// Style for a `Button` given this `Style`'s current state.
    pub fn button_style(&self, is_selected: bool) -> ButtonStyle {
        ButtonStyle {
            maybe_color: self.maybe_color.map(|c| if is_selected { c.highlighted() } else { c }),
            maybe_frame: self.maybe_frame,
            maybe_frame_color: self.maybe_frame_color,
            maybe_label_color: self.maybe_label_color,
            maybe_label_font_size: self.maybe_label_font_size,
        }
    }

}


impl<'a, F> Colorable for DropDownList<'a, F> {
    fn color(mut self, color: Color) -> Self {
        self.style.maybe_color = Some(color);
        self
    }
}

impl<'a, F> Frameable for DropDownList<'a, F> {
    fn frame(mut self, width: f64) -> Self {
        self.style.maybe_frame = Some(width);
        self
    }
    fn frame_color(mut self, color: Color) -> Self {
        self.style.maybe_frame_color = Some(color);
        self
    }
}

impl<'a, F> Labelable<'a> for DropDownList<'a, F> {
    fn label(mut self, text: &'a str) -> Self {
        self.maybe_label = Some(text);
        self
    }

    fn label_color(mut self, color: Color) -> Self {
        self.style.maybe_label_color = Some(color);
        self
    }

    fn label_font_size(mut self, size: FontSize) -> Self {
        self.style.maybe_label_font_size = Some(size);
        self
    }
}