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
extern crate pancurses;

pub fn line_ui<F>(lines_fn: F)
    where F: Fn(&str, VecPusher<String>)
{
    let window = pancurses::initscr();

    pancurses::noecho();

    let mut string = String::new();

    loop {
        let mut lines: Vec<String> = Vec::new();
        lines_fn(&string, VecPusher(&mut lines));

        for (row, line) in lines.iter().enumerate() {
            window.mvaddstr(row as i32, 0, line);
        }

        window.refresh();

        if let pancurses::Input::Character(c) = window.getch().unwrap() {
            match c {
                '' => {
                    break;
                },
                '' => {
                    string.pop();
                },
                _ => {
                    if is_input_character(c) {
                        string.push(c);
                    }
                },
            }
        }

        window.clear();
    }

    pancurses::endwin();
}

fn is_input_character(c: char) -> bool {
    c.is_alphanumeric() || "~!@#$%^&*()_+{}|:\"<>?`-=[]\\;',./".contains(c)
}

pub struct VecPusher<'a, T: 'a>(&'a mut Vec<T>);

impl<'a, T: 'a> VecPusher<'a, T> {
    pub fn push<V: Into<T>>(&mut self, value: V) {
        self.0.push(value.into());
    }
}