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
use std::io;
use std::io::{Read, Write};
use std::os::unix::io::{AsRawFd, RawFd};
use std::process;
use termios::*;

fn get_stdin_fd() -> RawFd {
    let stdin = io::stdin();
    stdin.as_raw_fd()
}

mod keys {
    pub(crate) const CTRL_A: u8 = 1;
    pub(crate) const CTRL_B: u8 = 2;
    pub(crate) const CTRL_C: u8 = 3;
    pub(crate) const CTRL_D: u8 = 4;
    pub(crate) const CTRL_E: u8 = 5;
    pub(crate) const CTRL_F: u8 = 6;
    pub(crate) const CTRL_H: u8 = 8;
    pub(crate) const CTRL_I: u8 = 9;
    pub(crate) const CTRL_J: u8 = 10;
    pub(crate) const CTRL_K: u8 = 11;
    pub(crate) const ENTER: u8 = 13;
    pub(crate) const ESC: u8 = 27;
    pub(crate) const ONE: u8 = 49;
    pub(crate) const TWO: u8 = 50;
    pub(crate) const THREE: u8 = 51;
    pub(crate) const FOUR: u8 = 52;
    pub(crate) const FIVE: u8 = 53;
    pub(crate) const SIX: u8 = 54;
    pub(crate) const A: u8 = 65;
    pub(crate) const B: u8 = 66;
    pub(crate) const C: u8 = 67;
    pub(crate) const D: u8 = 68;
    // This char is `[`.
    pub(crate) const LEFT_BRACKET: u8 = 91;
    pub(crate) const BACKSPACE: u8 = 127;
}

struct Line<'a> {
    backup: Termios,
    position: usize,
    buffer: &'a mut Vec<u8>,
    prompt: &'a [u8],
}

impl<'a> Line<'a> {
    fn new(buffer: &'a mut Vec<u8>, prompt: &'a [u8]) -> Self {
        let backup = Termios::from_fd(get_stdin_fd()).unwrap();
        Line::enable_raw_mode();
        Line {
            backup,
            position: 0,
            buffer,
            prompt,
        }
    }

    fn enable_raw_mode() {
        let fd = get_stdin_fd();
        let mut termios = Termios::from_fd(fd).unwrap();

        termios.c_iflag &= !(BRKINT | INPCK | ISTRIP | ICRNL | IXON);
        termios.c_oflag &= !OPOST;
        termios.c_cflag |= CS8;
        termios.c_lflag &= !(ECHO | ICANON | IEXTEN | ISIG);
        termios.c_cc[VMIN] = 1;
        termios.c_cc[VTIME] = 0;

        tcsetattr(fd, TCSANOW, &termios).unwrap();
        tcflush(fd, TCIOFLUSH).unwrap();
    }

    fn disable_raw_mode(&self) {
        let fd = get_stdin_fd();
        tcsetattr(fd, TCSANOW, &self.backup).unwrap();
        tcflush(fd, TCIOFLUSH).unwrap();
    }

    fn refresh_line(&self) -> io::Result<()> {
        let mut stdout = io::stdout();
        stdout.write_all(
            &[
                format!("\x1b[{}D\x1b[K", self.prompt.len() + self.buffer.len() + 1).as_bytes(),
                self.prompt,
                &self.buffer[..],
                format!("\r\x1b[{}C", self.position + self.prompt.len()).as_bytes(),
            ]
            .concat(),
        )?;
        stdout.flush()?;
        Ok(())
    }

    fn get(&mut self) -> io::Result<()> {
        let mut stdin = io::stdin();

        self.refresh_line()?;

        loop {
            let mut buf = vec![0; 1];
            let n = stdin.read(&mut buf)?;
            assert_eq!(n, 1);

            if buf[0] == keys::ESC {
                let mut buf2 = vec![0; 3];
                let n = stdin.read(&mut buf2[0..1])?;
                assert_eq!(n, 1);
                match buf2[0] {
                    // arrows, home, end or del
                    keys::LEFT_BRACKET => {
                        let n = stdin.read(&mut buf2[1..2])?;
                        assert_eq!(n, 1);
                        match buf2[1] {
                            // HOME
                            keys::ONE => {
                                let _ = stdin.read(&mut buf2[2..3])?;
                                buf[0] = keys::CTRL_A;
                            }
                            // INS
                            keys::TWO => {
                                let _ = stdin.read(&mut buf2[2..3])?;
                                continue;
                            }
                            // DEL
                            keys::THREE => {
                                let _ = stdin.read(&mut buf2[2..3])?;
                                if self.position < self.buffer.len() {
                                    buf[0] = keys::CTRL_D;
                                } else {
                                    continue;
                                }
                            }
                            // END
                            keys::FOUR => {
                                let _ = stdin.read(&mut buf2[2..3])?;
                                buf[0] = keys::CTRL_E;
                            }
                            // PgUp
                            keys::FIVE => {
                                let _ = stdin.read(&mut buf2[2..3])?;
                                continue;
                            }
                            // PgDn
                            keys::SIX => {
                                let _ = stdin.read(&mut buf2[2..3])?;
                                continue;
                            }
                            // Up
                            keys::A => {
                                continue;
                            }
                            // Down
                            keys::B => {
                                continue;
                            }
                            // Right
                            keys::C => {
                                buf[0] = keys::CTRL_F;
                            }
                            // Left
                            keys::D => {
                                buf[0] = keys::CTRL_B;
                            }
                            _ => {
                                continue;
                            }
                        }
                    }
                    _ => {
                        // handle to esc
                        // ...
                        buf[0] = buf2[0];
                    }
                }
            }

            match buf[0] {
                // Move the cursor start of line.
                keys::CTRL_A => {
                    self.position = 0;
                    self.refresh_line()?;
                }
                // Move the cursor forward 1 column.
                keys::CTRL_B => {
                    if self.position == 0 {
                        continue;
                    }
                    self.position -= 1;
                    self.refresh_line()?;
                }
                // Exit the process.
                keys::CTRL_C => {
                    self.disable_raw_mode();
                    process::exit(0);
                }
                keys::CTRL_D => {
                    // If the buffer is empty, exit the process.
                    if self.buffer.len() == 0 {
                        self.disable_raw_mode();
                        process::exit(0);
                    // Delete a char at the cursor.
                    } else if self.position < self.buffer.len() {
                        self.buffer.remove(self.position);
                        self.refresh_line()?;
                    }
                }
                // Move the cursor end of line.
                keys::CTRL_E => {
                    self.position = self.buffer.len();
                    self.refresh_line()?;
                }
                // Move the cursor backward 1 column.
                keys::CTRL_F => {
                    if self.position == self.buffer.len() {
                        continue;
                    }
                    self.position += 1;
                    self.refresh_line()?;
                }
                keys::CTRL_H | keys::BACKSPACE => {
                    if self.position == 0 || self.buffer.len() == 0 {
                        continue;
                    }
                    self.position -= 1;
                    self.buffer.remove(self.position);
                    self.refresh_line()?;
                }
                keys::CTRL_I => {
                    // TODO
                    continue;
                }
                keys::CTRL_J | keys::ENTER => {
                    break;
                }
                keys::CTRL_K => {
                    // TODO
                    continue;
                }
                // esc,
                keys::ESC => {
                    // TODO
                    continue;
                }
                _ => {
                    if self.position < self.buffer.len() {
                        self.buffer[self.position] = buf[0];
                    } else {
                        self.buffer.extend(&buf);
                    }
                    self.position += 1;
                    self.refresh_line()?;
                }
            }
        }
        let mut stdout = io::stdout();
        stdout.write_all(format!("\n\x1b[{}D", self.prompt.len() + self.position).as_bytes())?;
        stdout.flush()?;
        Ok(())
    }
}

impl<'a> Drop for Line<'a> {
    fn drop(&mut self) {
        self.disable_raw_mode()
    }
}

pub struct Interaction {
    prompt: Vec<u8>,
}

impl Interaction {
    pub fn new() -> Self {
        Interaction { prompt: vec![0; 0] }
    }

    pub fn from(prompt: &[u8]) -> Self {
        Interaction {
            prompt: prompt.to_vec(),
        }
    }

    pub fn from_str(prompt: &str) -> Self {
        Interaction {
            prompt: prompt.as_bytes().to_vec(),
        }
    }

    pub fn line(&mut self) -> io::Result<Vec<u8>> {
        let mut buffer = vec![0; 0];
        Line::new(&mut buffer, &self.prompt).get()?;
        Ok(buffer)
    }

    pub fn set_prompt(&mut self, prompt: &[u8]) {
        self.prompt = prompt.to_vec()
    }
}