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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
use std::fmt;
use std::io::{Read, Write, Result, Error, ErrorKind};
use std::iter::Peekable;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Sequence<'a> {
    /// Reset all terminal settings to default.
    Reset,

    /// Enable/disable line wrapping.
    LineWrap(bool),

    /// Set default font.
    FontDefault,

    /// Set alternate font.
    FontAlternate,

    /// Set the cursor position (row, column).
    CursorAt(u32, u32),

    /// Move the cursor position by the given delta (row, column).
    ///
    /// (0, 0) is at the top left of the screen.
    CursorMove(i32, i32),

    /// Save the cursor position.
    CursorSave,

    /// Resotre the saved cursor position.
    CursorRestore,

    /// Save the cursor position and attributes.
    CursorSaveAttributes,

    /// Resotre the saved cursor position and attributes.
    CursorRestoreAttributes,

    /// Enable scrolling.
    ///
    /// If `None` is passed then scrolling is enabled for the whole screen.
    /// If `Some((start, end))` is passed then scrolling is enabled from row `start` to `end`.
    ScrollEnable(Option<(u32, u32)>),

    /// Scroll by the given number of rows.
    /// Positive rows means scrolling down, negative rows means scrolling up.
    Scroll(i32),

    /// Erases from the current cursor position to the end of the current line.
    EraseEndOfLine,

    /// Erases from the current cursor position to the start of the current line.
    EraseStartOfLine,

    /// Erases the entire current line.
    EraseLine,

    /// Erases the screen from the current line down to the bottom of the screen.
    EraseDown,

    /// Erases the screen from the current line up to the top of the screen.
    EraseUp,

    /// Erases the screen with the background colour and moves the cursor to home.
    EraseScreen,

    /// Sets display attributes.
    SetAttributes(&'a [Attribute])
}

/// Display attributes.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Attribute {
    /// Reset all attributes.
    Default,

    /// Set the text bright.
    Bright,

    /// Set the text dim.
    Dim,

    /// Underscore the text.
    Underscore,

    /// Make the text blink.
    Blink,

    /// Reverse.
    Reverse,

    /// Hides the cursor.
    Hidden,

    /// Set the background color.
    Foreground(Color),

    /// Set the foreground color.
    Background(Color)
}

/// Standard colors.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Color {
    Black,
    Red,
    Green,
    Yellow,
    Blue,
    Magenta,
    Cyan,
    White
}

impl<'a> fmt::Display for Sequence<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Sequence::*;
        match self {
            Reset => write!(f, "\x1bc"),
            LineWrap(true) => write!(f, "\x1b[7h"),
            LineWrap(false) => write!(f, "\x1b[7l"),
            FontDefault => write!(f, "\x1b("),
            FontAlternate => write!(f, "\x1b)"),
            CursorAt(row, column) => write!(f, "\x1b[{};{}H", row, column),
            CursorMove(drow, dcolumn) => {
                if *drow != 0 {
                    if *drow < 0 {
                        write!(f, "\x1b[{}A", -drow)?;
                    } else {
                        write!(f, "\x1b[{}B", drow)?;
                    }
                }
                if *dcolumn != 0 {
                    if *dcolumn > 0 {
                        write!(f, "\x1b[{}C", dcolumn)?;
                    } else {
                        write!(f, "\x1b[{}D", -dcolumn)?;
                    }
                }
                Ok(())
            },
            CursorSave => write!(f, "\x1b[s"),
            CursorRestore => write!(f, "\x1b[u"),
            CursorSaveAttributes => write!(f, "\x1b7"),
            CursorRestoreAttributes => write!(f, "\x1b8"),
            ScrollEnable(None) => write!(f, "\x1b[r"),
            ScrollEnable(Some((start, end))) => write!(f, "\x1b[{};{}r", start, end),
            Scroll(d) => {
                if *d < 0 {
                    for _ in 0..(-*d) {
                        write!(f, "\x1b[D")?;
                    }
                } else {
                    for _ in 0..*d {
                        write!(f, "\x1b[M")?;
                    }
                }
                Ok(())
            },
            EraseEndOfLine => write!(f, "\x1b[K"),
            EraseStartOfLine => write!(f, "\x1b[1K"),
            EraseLine => write!(f, "\x1b[2K"),
            EraseDown => write!(f, "\x1b[J"),
            EraseUp => write!(f, "\x1b[1J"),
            EraseScreen => write!(f, "\x1b[2J"),
            SetAttributes(attributes) => {
                write!(f, "\x1b[{}m", DisplayAttributes(attributes))
            }
        }
    }
}

impl fmt::Display for Attribute {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Attribute::*;
        match self {
            Default => write!(f, "0"),
            Bright => write!(f, "1"),
            Dim => write!(f, "2"),
            Underscore => write!(f, "4"),
            Blink => write!(f, "5"),
            Reverse => write!(f, "7"),
            Hidden => write!(f, "8"),
            Foreground(c) => write!(f, "{}", 30+c.index()),
            Background(c) => write!(f, "{}", 40+c.index()),
        }
    }
}

impl Color {
    /// Return the index of the color.
    ///
    /// Used to format color attributes.
    pub fn index(&self) -> u8 {
        use Color::*;
        match self {
            Black => 0,
            Red => 1,
            Green => 2,
            Yellow => 3,
            Blue => 4,
            Magenta => 5,
            Cyan => 6,
            White => 7
        }
    }
}

struct DisplayAttributes<'a>(&'a [Attribute]);

impl<'a> fmt::Display for DisplayAttributes<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.0.split_first() {
            Some((head, tail)) => {
                write!(f, "{}", head)?;
                for a in tail {
                    write!(f, ";{}", a)?;
                }
                Ok(())
            },
            None => Ok(())
        }
    }
}

/// Client queries.
pub enum Query {
    /// Get the cursor position.
    CursorPosition
}

impl fmt::Display for Query {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use Query::*;
        match self {
            CursorPosition => write!(f, "\x1b[6n")
        }
    }
}

/// Device responses.
pub enum Response {
    /// Cursor position informations.
    CursorPosition(u32, u32)
}

/// A device handling escapes sequences.
pub struct Device<I: Read, O: Write> {
    input: I,
    output: O,
    buffer: Vec<u8>,
    offset: usize
}

impl<I: Read, O: Write> Device<I, O> {
    /// Create a new device from an input and output.
    pub fn new(input: I, output: O) -> Device<I, O> {
        Device {
            input: input,
            output: output,
            buffer: Vec::new(),
            offset: 0
        }
    }

    /// Read the next byte out of the input stream.
    fn next_byte(&mut self) -> Result<Option<u8>> {
        let mut buffer = [0];
        let n = self.input.read(&mut buffer)?;
        if n == 0 {
            Ok(None)
        } else {
            Ok(Some(buffer[0]))
        }
    }

    /// Wait for the device response.
    ///
    /// Any eventual data arrived before the device response is buffered so it can be
    /// later outputed to a reader.
    fn response(&mut self) -> Result<Response> {
        loop {
            match self.next_byte()? {
                Some(0x1b) => {
                    return self.parse_response()
                },
                Some(c) => {
                    self.buffer.push(c)
                },
                None => return Err(Error::new(ErrorKind::UnexpectedEof, "no response from the device"))
            }
        }
    }

    /// Parse a device response, after the initial `<ESC>` character.
    fn parse_response(&mut self) -> Result<Response> {
        let mut buffer = Vec::new();
        loop {
            match self.next_byte()? {
                Some(c) => {
                    match c {
                        0x52 => { // [{ROW};{COLUMN}R: Cursor position
                            let mut it = buffer.into_iter().peekable();
                            expect_byte(&mut it, 0x5b)?; // [
                            let row = read_u32(&mut it)?; // {ROW}
                            expect_byte(&mut it, 0x3b)?; // ;
                            let column = read_u32(&mut it)?; // {COLUMN}

                            return Ok(Response::CursorPosition(row-1, column-1))
                        },
                        _ => {
                            buffer.push(c)
                        }
                    }
                },
                None => return Err(Error::new(ErrorKind::UnexpectedEof, "incomplete device response"))
            }
        }
    }

    /// Requests the cursor position on the device.
    ///
    /// The output format is `(row, column)`.
    #[allow(irrefutable_let_patterns)]
    pub fn cursor_position(&mut self) -> Result<(u32, u32)> {
        write!(self.output, "{}", Query::CursorPosition)?;
        self.flush()?;
        if let Response::CursorPosition(x, y) = self.response()? {
            Ok((x, y))
        } else {
            Err(Error::new(ErrorKind::InvalidData, "invalid device response"))
        }
    }

    /// Reset all terminal settings to default.
    pub fn reset(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::Reset)
    }

    /// Enable/disable line wrapping.
    pub fn line_wrap(&mut self, enable: bool) -> Result<()> {
        write!(self.output, "{}", Sequence::LineWrap(enable))
    }

    /// Set default font.
    pub fn font_default(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::FontDefault)
    }

    /// Set alternate font.
    pub fn font_alternate(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::FontAlternate)
    }

    /// Set the cursor position.
    pub fn cursor_at(&mut self, row: u32, column: u32) -> Result<()> {
        write!(self.output, "{}", Sequence::CursorAt(row, column))
    }

    /// Move the cursor position by the given delta.
    ///
    /// (0, 0) is at the top left of the screen.
    pub fn cursor_move(&mut self, drow: i32, dcolumn: i32) -> Result<()> {
        write!(self.output, "{}", Sequence::CursorMove(drow, dcolumn))
    }

    /// Save the cursor position.
    pub fn cursor_save(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::CursorSave)
    }

    /// Resotre the saved cursor position.
    pub fn cursor_restore(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::CursorRestore)
    }

    /// Save the cursor position.
    pub fn cursor_save_attributes(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::CursorSaveAttributes)
    }

    /// Resotre the saved cursor position.
    pub fn cursor_restore_attributes(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::CursorRestoreAttributes)
    }

    /// Enable scrolling.
    ///
    /// If `None` is passed then scrolling is enabled for the whole screen.
    /// If `Some((start, end))` is passed then scrolling is enabled from row `start` to `end`.
    pub fn scroll_enable(&mut self, region: Option<(u32, u32)>) -> Result<()> {
        write!(self.output, "{}", Sequence::ScrollEnable(region))
    }

    /// Scroll by the given number of rows.
    /// Positive rows means scrolling down, negative rows means scrolling up.
    pub fn scroll(&mut self, rows: i32) -> Result<()> {
        write!(self.output, "{}", Sequence::Scroll(rows))
    }

    /// Erases from the current cursor position to the end of the current line.
    pub fn erase_end_of_line(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::EraseEndOfLine)
    }

    /// Erases from the current cursor position to the start of the current line.
    pub fn erase_start_of_line(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::EraseStartOfLine)
    }

    /// Erases the entire current line.
    pub fn erase_line(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::EraseLine)
    }

    /// Erases the screen from the current line down to the bottom of the screen.
    pub fn erase_down(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::EraseDown)
    }

    /// Erases the screen from the current line up to the top of the screen.
    pub fn erase_up(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::EraseUp)
    }

    /// Erases the screen with the background colour and moves the cursor to home.
    pub fn erase_screen(&mut self) -> Result<()> {
        write!(self.output, "{}", Sequence::EraseScreen)
    }

    /// Sets display attributes.
    pub fn set_attributes(&mut self, attributes: &[Attribute]) -> Result<()> {
        write!(self.output, "{}", Sequence::SetAttributes(attributes))
    }
}

/// Read the expected byte out of the given peekable iterator, or return an error.
fn expect_byte<I: Iterator<Item = u8>>(it: &mut Peekable<I>, expected: u8) -> Result<()> {
    match it.next() {
        Some(b) if b == expected => Ok(()),
        _ => Err(Error::new(ErrorKind::InvalidData, "invalid device response"))
    }
}

/// Read a `u32` out of the given peekable iterator, or return an error.
fn read_u32<I: Iterator<Item = u8>>(it: &mut Peekable<I>) -> Result<u32> {
    let mut empty = true;
    let mut value = 0u32;

    loop {
        match it.peek() {
            Some(b) => {
                if *b >= 0x30 && *b <= 0x39 {
                    let b = it.next().unwrap();
                    empty = false;
                    value = value * 10 + (b - 0x30) as u32;
                } else {
                    break
                }
            },
            None => {
                break
            }
        }
    }

    if empty {
        Err(Error::new(ErrorKind::InvalidData, "invalid device response"))
    } else {
        Ok(value)
    }
}

impl<I: Read, O: Write> Read for Device<I, O> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
        let len = std::cmp::min(self.buffer.len()-self.offset, buf.len());
        if len > 0 {
            for i in 0..len {
                buf[i] = self.buffer[self.offset];
                self.offset += 1;
            }

            if self.offset >= self.buffer.len() {
                self.offset = 0;
                self.buffer.clear();
            }
        }

        Ok(self.input.read(&mut buf[len..])? + len)
    }
}

impl<I: Read, O: Write> Write for Device<I, O> {
    fn write(&mut self, buf: &[u8]) -> Result<usize> {
        self.output.write(buf)
    }

    fn flush(&mut self) -> Result<()> {
        self.output.flush()
    }
}