aboutsummaryrefslogtreecommitdiffstats
path: root/src/window.rs
blob: f01cfe9338ee6e671e3daa15d0737f5e25588ce6 (plain) (blame)
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
//! A window is an abstraction for the UI. Buffers (like [Threads]) draw "to" windows.

use std::io::Write;
use termion::{clear, color, cursor};

#[derive(Clone, Copy)]
pub struct Area {
    pub x: u16,
    pub y: u16,
    pub w: u16,
    pub h: u16,
}

pub enum Line {
    Normal(String),
    Highlight(String),
}

pub struct Window {
    pub lines: Vec<Line>,
}

impl Window {
    pub fn new() -> Self {
        Self {
            lines: Vec::new(),
        }
    }

    pub fn draw<W: Write>(&mut self, out: &mut W, area: Area) -> Result<(), std::io::Error> {
        let mut y = area.y;
        let mut lines = self.lines.iter();
        while y < area.h + 1 {
            match lines.next() {
                Some(line) => {
                    write!(out, "{}", cursor::Goto(area.x, y))?;
                    match line {
                        Line::Normal(s) => write!(out, "{}", s)?,
                        Line::Highlight(s) => write!(
                            out,
                            "{}{}{}",
                            color::Fg(color::Red),
                            s,
                            color::Fg(color::Reset),
                        )?,
                    }
                    y += 1;
                }
                None => break,
            }
        }
        out.flush()?;

        self.lines.clear();
        Ok(())
    }
}