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
use {
    crate::{
        Area,
        CompoundStyle,
        Error,
        Event,
        fit,
    },
    std::io::Write,
    crossterm::{
        cursor,
        event::{
            KeyCode,
            KeyEvent,
            KeyModifiers,
        },
        queue,
        style::{
            Attribute,
            Color,
            SetBackgroundColor,
        },
    },
};

/// A simple input field, managing its cursor position and
/// either handling the events you give it or being managed
/// through direct manipulation functions
/// (put_char, del_char_left, etc.)
pub struct InputField {
    content: Vec<char>,
    cursor_pos: usize, // position in chars
    pub area: Area,
    normal_style: CompoundStyle,
    cursor_style: CompoundStyle,
    pub focused: bool,
}

impl InputField {
    pub fn new(area: Area) -> Self {
        debug_assert!(area.height == 1, "input area must be of height 1");
        let normal_style = CompoundStyle::default();
        let mut cursor_style = normal_style.clone();
        cursor_style.add_attr(Attribute::Reverse);
        let focused = true;
        Self {
            content: Vec::new(),
            area,
            cursor_pos: 0,
            normal_style,
            cursor_style,
            focused,
        }
    }
    pub fn change_area(&mut self, x: u16, y: u16, w: u16) {
        self.area.left = x;
        self.area.top = y;
        self.area.width = w;
    }
    pub fn set_normal_style(&mut self, style: CompoundStyle) {
        self.normal_style = style;
        self.cursor_style = self.normal_style.clone();
        self.cursor_style.add_attr(Attribute::Reverse);
    }
    pub fn get_content(&self) -> String {
        self.content.iter().collect()
    }
    /// tell whether the content of the input is equal
    ///  to the argument
    pub fn is_content(&self, s: &str) -> bool {
        // TODO this comparison could be optimized
        let str_content = self.get_content();
        str_content == s
    }
    /// change the content to the new one and
    ///  put the cursor at the end **if** the
    ///  content is different from the previous one.
    pub fn set_content(&mut self, s: &str) {
        if self.is_content(s) {
            return;
        }
        self.content = s.chars().collect();
        self.cursor_pos = self.content.len();
    }
    /// put a char at cursor position (and increment this
    /// position)
    pub fn put_char(&mut self, c: char) -> bool {
        self.content.insert(self.cursor_pos, c);
        self.cursor_pos += 1;
        true
    }
    /// remove the char left of the cursor, if any
    pub fn del_char_left(&mut self) -> bool {
        if self.cursor_pos > 0 {
            self.cursor_pos -= 1;
            self.content.remove(self.cursor_pos);
            true
        } else {
            false
        }
    }
    /// remove the char at cursor position, if any
    pub fn del_char_below(&mut self) -> bool {
        if self.cursor_pos < self.content.len() {
            self.content.remove(self.cursor_pos);
            true
        } else {
            false
        }
    }
    pub fn move_right(&mut self) -> bool {
        if self.cursor_pos < self.content.len() {
            self.cursor_pos += 1;
            true
        } else {
            false
        }
    }
    pub fn move_left(&mut self) -> bool {
        if self.cursor_pos > 0 {
            self.cursor_pos -= 1;
            true
        } else {
            false
        }
    }
    pub fn move_to_end(&mut self) -> bool {
        if self.cursor_pos < self.content.len() {
            self.cursor_pos = self.content.len();
            true
        } else {
            false
        }
    }
    pub fn move_to_start(&mut self) -> bool {
        if self.cursor_pos > 0 {
            self.cursor_pos = 0;
            true
        } else {
            false
        }
    }
    pub fn move_word_left(&mut self) -> bool {
        if self.cursor_pos == 0 {
            return false;
        }
        loop {
            self.cursor_pos -= 1;
            if self.cursor_pos == 0 || !self.content[self.cursor_pos-1].is_alphanumeric() {
                break;
            }
        }
        true
    }
    pub fn move_word_right(&mut self) -> bool {
        if self.cursor_pos == self.content.len() {
            return false;
        }
        loop {
            self.cursor_pos += 1;
            if self.cursor_pos >= self.content.len() - 1
                || !self.content[self.cursor_pos-1].is_alphanumeric() {
                break;
            }
        }
        true
    }
    pub fn del_word_left(&mut self) -> bool {
        if self.cursor_pos == 0 {
            return false;
        }
        loop {
            self.content.remove(self.cursor_pos);
            self.cursor_pos -= 1;
            if self.cursor_pos == 0 || !self.content[self.cursor_pos-1].is_alphanumeric() {
                break;
            }
        }
        true
    }
    pub fn del_word_right(&mut self) -> bool {
        if self.cursor_pos == self.content.len() {
            return false;
        }
        loop {
            let deleted_is_an = self.content[self.cursor_pos].is_alphanumeric();
            self.content.remove(self.cursor_pos);
            if self.cursor_pos >= self.content.len() - 1 || !deleted_is_an {
                break;
            }
        }
        true
    }

    /// apply an event being a key without modifier.
    ///
    /// You don't usually call this function but the more
    /// general `apply_event`. This one is useful when you
    /// manage events mostly yourselves.
    ///
    /// This function handles a few events like deleting a
    /// char, or going to the start (home key) or end (end key)
    /// of the input. If you want to totally handle events, you
    /// may call function like `put_char` and `del_char_left`
    /// directly.
    pub fn apply_keycode_event(&mut self, code: KeyCode) -> bool {
        if !self.focused {
            return false;
        }
        match code {
            KeyCode::Home => self.move_to_start(),
            KeyCode::End => self.move_to_end(),
            KeyCode::Char(c) => self.put_char(c),
            KeyCode::Left => self.move_left(),
            KeyCode::Right => self.move_right(),
            KeyCode::Backspace => self.del_char_left(),
            KeyCode::Delete => self.del_char_below(),
            _ => false,
        }
    }

    /// apply a click event
    ///
    /// (for when you handle the events yourselves and don't
    ///  have a termimad event)
    pub fn apply_click_event(&mut self, x: u16, y: u16) -> bool {
        if self.area.contains(x, y) {
            if self.focused {
                let p = (x - 1 - self.area.left) as usize;
                self.cursor_pos = p.min(self.content.len());
            } else {
                self.focused = true;
            }
            true
        } else {
            false
        }
    }

    /// apply the passed event to change the state (content, cursor)
    ///
    /// Return true when the event was used.
    pub fn apply_event(&mut self, event: &Event) -> bool {
        match event {
            Event::Click(x, y, ..) => {
                self.apply_click_event(*x, *y)
            }
            Event::Key(KeyEvent{code, modifiers}) if (modifiers.is_empty()||*modifiers==KeyModifiers::SHIFT) => {
                self.apply_keycode_event(*code)
            }
            _ => false,
        }
    }

    /// render the input field on screen.
    ///
    /// All rendering must be explicitely called, no rendering is
    /// done on functions changing the state.
    ///
    /// w is typically either stderr or stdout.
    pub fn display_on<W>(&self, w: &mut W) -> Result<(), Error>
    where
        W: std::io::Write,
    {
        queue!(w, SetBackgroundColor(Color::Reset))?;
        queue!(w, cursor::MoveTo(self.area.left, self.area.top))?;

        let mut slice_start = 0;
        let width = self.area.width as usize;
        let mut ellipsis_at_start = false;
        let mut ellipsis_at_end = false;
        if self.content.len() + 1 >= width {
            if self.cursor_pos <= width / 2 {
                slice_start = 0;
                ellipsis_at_end = true;
            } else if self.cursor_pos >= self.content.len() - width / 2 {
                slice_start = self.content.len() + 1 - width;
                ellipsis_at_start = true;
            } else {
                slice_start = self.cursor_pos - width / 2;
                ellipsis_at_start = true;
                ellipsis_at_end = true;
            }
        }
        for i in 0..width {
            if i == 0 && ellipsis_at_start {
                self.normal_style.queue(w, fit::ELLIPSIS)?;
                continue;
            }
            if i == width-1 && ellipsis_at_end {
                self.normal_style.queue(w, fit::ELLIPSIS)?;
                continue;
            }
            let idx = i + slice_start;
            if idx >= self.content.len() {
                if self.focused && (idx==self.cursor_pos) && (idx==self.content.len()) {
                    self.cursor_style.queue(w, ' ')?;
                } else {
                    self.normal_style.queue(w, ' ')?;
                }
            } else {
                let c = self.content[idx];
                if self.focused && (self.cursor_pos == idx) {
                    self.cursor_style.queue(w, c)?;
                } else {
                    self.normal_style.queue(w, c)?;
                }
            }
        }
        Ok(())
    }

    /// render the input field on stdout
    pub fn display(&self) -> Result<(), Error> {
        let mut w = std::io::stdout();
        self.display_on(&mut w)?;
        w.flush()?;
        Ok(())
    }
}