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
use geom::{Distance, Polygon, Pt2D};

use crate::{
    Btn, Button, Choice, Color, EventCtx, GeomBatch, GfxCtx, Menu, Outcome, ScreenDims, ScreenPt,
    ScreenRectangle, WidgetImpl, WidgetOutput,
};

pub struct Dropdown<T: Clone> {
    current_idx: usize,
    btn: Button,
    // TODO Why not T?
    menu: Option<Menu<usize>>,
    label: String,
    blank_btn_label: bool,

    choices: Vec<Choice<T>>,
}

impl<T: 'static + PartialEq + Clone + std::fmt::Debug> Dropdown<T> {
    pub fn new(
        ctx: &EventCtx,
        label: &str,
        default_value: T,
        choices: Vec<Choice<T>>,
        // TODO Ideally builder style
        blank_btn_label: bool,
    ) -> Dropdown<T> {
        let current_idx = if let Some(idx) = choices.iter().position(|c| c.data == default_value) {
            idx
        } else {
            panic!(
                "Dropdown {} has default_value {:?}, but none of the choices match that",
                label, default_value
            );
        };

        Dropdown {
            current_idx,
            btn: make_btn(ctx, &choices[current_idx].label, label, blank_btn_label),
            menu: None,
            label: label.to_string(),
            blank_btn_label,
            choices,
        }
    }
}

impl<T: 'static + PartialEq + Clone> Dropdown<T> {
    pub fn current_value(&self) -> T {
        self.choices[self.current_idx].data.clone()
    }
    pub(crate) fn current_value_label(&self) -> String {
        self.choices[self.current_idx].label.clone()
    }
}

impl<T: 'static + Clone> Dropdown<T> {
    fn open_menu(&mut self, ctx: &mut EventCtx) {
        // TODO set current idx in menu
        let mut menu = Menu::new(
            ctx,
            self.choices
                .iter()
                .enumerate()
                .map(|(idx, c)| c.with_value(idx))
                .collect(),
        )
        .take_menu();
        let y1_below = self.btn.top_left.y + self.btn.dims.height + 15.0;

        menu.set_pos(ScreenPt::new(
            self.btn.top_left.x,
            // top_left_for_corner doesn't quite work
            if y1_below + menu.get_dims().height < ctx.canvas.window_height {
                y1_below
            } else {
                self.btn.top_left.y - 15.0 - menu.get_dims().height
            },
        ));
        self.menu = Some(menu);
    }
}

impl<T: 'static + Clone> WidgetImpl for Dropdown<T> {
    fn get_dims(&self) -> ScreenDims {
        self.btn.get_dims()
    }

    fn set_pos(&mut self, top_left: ScreenPt) {
        self.btn.set_pos(top_left);
    }

    fn event(&mut self, ctx: &mut EventCtx, output: &mut WidgetOutput) {
        if let Some(ref mut m) = self.menu {
            let mut tmp_ouput = WidgetOutput::new();
            m.event(ctx, &mut tmp_ouput);
            if let Outcome::Clicked(_) = tmp_ouput.outcome {
                self.current_idx = self.menu.take().unwrap().take_current_choice();
                output.outcome = Outcome::Changed;
                let top_left = self.btn.top_left;
                self.btn = make_btn(
                    ctx,
                    &self.choices[self.current_idx].label,
                    &self.label,
                    self.blank_btn_label,
                );
                self.btn.set_pos(top_left);
                output.redo_layout = true;
            } else if ctx.normal_left_click() {
                if let Some(pt) = ctx.canvas.get_cursor_in_screen_space() {
                    if !ScreenRectangle::top_left(m.top_left, m.get_dims()).contains(pt) {
                        self.menu = None;
                    }
                } else {
                    self.menu = None;
                }
                if self.menu.is_some() {
                    ctx.input.unconsume_event();
                }
            }
        } else {
            self.btn.event(ctx, output);
            if let Outcome::Clicked(_) = output.outcome {
                output.outcome = Outcome::Nothing;
                self.open_menu(ctx);
            }
        }
    }

    fn draw(&self, g: &mut GfxCtx) {
        self.btn.draw(g);
        if let Some(ref m) = self.menu {
            // We need a background too! Add some padding and an outline.
            // TODO Little embedded Panel could make more sense?
            let pad = 5.0;
            let width = m.get_dims().width + 2.0 * pad;
            let height = m.get_dims().height + 2.0 * pad;
            let rect = Polygon::rounded_rectangle(width, height, Some(5.0));
            let draw_bg = g.upload(GeomBatch::from(vec![
                (Color::grey(0.3), rect.clone()),
                (
                    Color::WHITE,
                    rect.to_outline(Distance::meters(3.0)).unwrap(),
                ),
            ]));
            g.fork(
                Pt2D::new(0.0, 0.0),
                ScreenPt::new(m.top_left.x - pad, m.top_left.y - pad),
                1.0,
                Some(crate::drawing::MENU_Z),
            );
            g.redraw(&draw_bg);
            g.unfork();

            m.draw(g);

            // Dropdown menus often leak out of their Panel
            g.canvas
                .mark_covered_area(ScreenRectangle::top_left(m.top_left, m.get_dims()));
        }
    }

    fn can_restore(&self) -> bool {
        true
    }
    fn restore(&mut self, ctx: &mut EventCtx, prev: &Box<dyn WidgetImpl>) {
        let prev = prev.downcast_ref::<Dropdown<T>>().unwrap();
        if prev.menu.is_some() {
            self.open_menu(ctx);
            // TODO Preserve menu hovered item. Only matters if we've moved the cursor off the
            // menu.
        }
    }
}

fn make_btn(ctx: &EventCtx, label: &str, tooltip: &str, blank_btn_label: bool) -> Button {
    let button_label = if blank_btn_label { None } else { Some(label) };
    Btn::pop_up(ctx, button_label)
        .build(ctx, tooltip, None)
        .take_btn()
}