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

use crate::{
    EdgeInsets, EventCtx, GeomBatch, GfxCtx, Key, Line, Outcome, ScreenDims, ScreenPt,
    ScreenRectangle, Style, Text, Widget, WidgetImpl, WidgetOutput,
};

// TODO right now, only a single line
// TODO max_chars isn't enforced; you can type as much as you want...

pub struct TextBox {
    line: String,
    label: String,
    cursor_x: usize,
    has_focus: bool,
    autofocus: bool,
    padding: EdgeInsets,

    top_left: ScreenPt,
    dims: ScreenDims,
}

impl TextBox {
    // TODO Really should have an options struct with defaults
    pub fn default_widget<I: Into<String>>(ctx: &EventCtx, label: I, prefilled: String) -> Widget {
        TextBox::widget(ctx, label, prefilled, true, 50)
    }

    /// `autofocus` means the text box always has focus; it'll consume all key events.
    pub fn widget<I: Into<String>>(
        ctx: &EventCtx,
        label: I,
        prefilled: String,
        autofocus: bool,
        max_chars: usize,
    ) -> Widget {
        let label = label.into();
        Widget::new(Box::new(TextBox::new(
            ctx,
            label.clone(),
            max_chars,
            prefilled,
            autofocus,
        )))
        .named(label)
    }

    pub(crate) fn new(
        ctx: &EventCtx,
        label: String,
        max_chars: usize,
        prefilled: String,
        autofocus: bool,
    ) -> TextBox {
        let padding = EdgeInsets {
            top: 6.0,
            left: 8.0,
            bottom: 8.0,
            right: 8.0,
        };
        let max_char_width = 25.0;
        Self {
            label,
            cursor_x: prefilled.len(),
            line: prefilled,
            has_focus: false,
            autofocus,
            padding,
            top_left: ScreenPt::new(0.0, 0.0),
            dims: ScreenDims::new(
                (max_chars as f64) * max_char_width + (padding.left + padding.right) as f64,
                ctx.default_line_height() + (padding.top + padding.bottom) as f64,
            ),
        }
    }

    fn calculate_text(&self, style: &Style) -> Text {
        let mut txt = Text::from(&self.line[0..self.cursor_x]);
        if self.cursor_x < self.line.len() {
            // TODO This "cursor" looks awful!
            txt.append_all(vec![
                Line("|").fg(style.text_primary_color),
                Line(&self.line[self.cursor_x..=self.cursor_x]),
                Line(&self.line[self.cursor_x + 1..]),
            ]);
        } else {
            txt.append(Line("|").fg(style.text_primary_color));
        }
        txt
    }

    pub fn get_line(&self) -> String {
        self.line.clone()
    }
}

impl WidgetImpl for TextBox {
    fn get_dims(&self) -> ScreenDims {
        self.dims
    }

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

    fn event(&mut self, ctx: &mut EventCtx, output: &mut WidgetOutput) {
        if !self.autofocus && ctx.redo_mouseover() {
            if let Some(pt) = ctx.canvas.get_cursor_in_screen_space() {
                self.has_focus = ScreenRectangle::top_left(self.top_left, self.dims).contains(pt);
            } else {
                self.has_focus = false;
            }
        }

        if !self.autofocus && !self.has_focus {
            return;
        }
        if let Some(key) = ctx.input.any_pressed() {
            match key {
                Key::LeftArrow => {
                    if self.cursor_x > 0 {
                        self.cursor_x -= 1;
                    }
                }
                Key::RightArrow => {
                    self.cursor_x = (self.cursor_x + 1).min(self.line.len());
                }
                Key::Backspace => {
                    if self.cursor_x > 0 {
                        output.outcome = Outcome::Changed(self.label.clone());
                        self.line.remove(self.cursor_x - 1);
                        self.cursor_x -= 1;
                    }
                }
                _ => {
                    if let Some(c) = key.to_char(ctx.is_key_down(Key::LeftShift)) {
                        output.outcome = Outcome::Changed(self.label.clone());
                        self.line.insert(self.cursor_x, c);
                        self.cursor_x += 1;
                    } else {
                        ctx.input.unconsume_event();
                    }
                }
            };
        }
    }

    fn draw(&self, g: &mut GfxCtx) {
        // TODO Cache
        let mut batch = GeomBatch::from(vec![(
            if self.autofocus || self.has_focus {
                g.style().field_bg
            } else {
                g.style().field_bg.dull(0.5)
            },
            Polygon::rounded_rectangle(self.dims.width, self.dims.height, 2.0),
        )]);

        let outline_style = g.style().btn_outline.outline;
        batch.push(
            outline_style.1,
            Polygon::rounded_rectangle(self.dims.width, self.dims.height, 2.0)
                .to_outline(Distance::meters(outline_style.0)),
        );

        batch.append(
            self.calculate_text(g.style())
                .render_autocropped(g)
                .translate(self.padding.left, self.padding.top),
        );
        let draw = g.upload(batch);
        g.redraw_at(self.top_left, &draw);
    }
}