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
use std::io::Write;
use termion::event::Key;
use termion::input::TermRead;
use termion::color;
use termion::cursor;
use termion::clear;
use termion::style::Reset;
use termion::raw::IntoRawMode;
use std::collections::HashMap;

/// Error during `wait_for_input`
#[derive(Debug)]
pub enum SentakuError {
    EmptyList,
    Canceled,
    IoError(std::io::Error),
}

impl std::convert::From<std::io::Error> for SentakuError {
    fn from(e: std::io::Error) -> SentakuError {
        SentakuError::IoError(e)
    }
}

/// Structure for each item to be chosen by the user
/// `label` will be displayed and `value` will be returned when the user select the item
pub struct SentakuItem<T> {
    label: String,
    value: T,
}

impl SentakuItem<String> {
    /// construct `SentakuItem`. `value` will be the same as `label`.
    pub fn from_str(label: &str) -> Self {
        SentakuItem {
            label: String::from(label),
            value: String::from(label),
        }
    }
}

pub enum SentakuAction<'a, T> {
    Up,
    Down,
    Cancel,
    Select,
    Action(Box<dyn Fn(&'a T) + 'a>),
}

impl<T> SentakuItem<T> {
    /// construct `SentakuItem`.
    pub fn new(label: &str, value: T) -> Self {
        SentakuItem {
            label: String::from(label),
            value,
        }
    }
}

fn display_items<T>(stdout: &mut std::io::Stdout, items: &Vec<SentakuItem<T>>, pos: usize) -> Result<(), std::io::Error> {
    for i in 0..items.len() {
        let item = &items[i];
        if pos == i {
            write!(stdout, "{}{}{}{}\r\n", color::Bg(color::Black), color::Fg(color::White), item.label, Reset)?;
        } else {
            write!(stdout, "{}\r\n", item.label)?;
        }
    }
    stdout.flush()?;
    Ok(())
}

/// Get default keymap
/// `Key::Up`: move cursor up
/// `Key::Down`: move cursor down
/// `Key::Char('\n')`: select current item
/// `Key::Ctrl('c')`: cancel current selection
pub fn get_default_keymap<'a, T>() -> HashMap<Key, SentakuAction<'a, T>> {
    let mut result = HashMap::new();
    result.insert(Key::Up, SentakuAction::Up);
    result.insert(Key::Down, SentakuAction::Down);
    result.insert(Key::Char('\n'), SentakuAction::Select);
    result.insert(Key::Ctrl('c'), SentakuAction::Cancel);

    result
}

/// Wait for user input and return an item user selects
/// If the user cancels the input or error happens in stdio, it returns `SentakuError`.
/// If `items` is an empty list, it also returns `SentakuError`.
pub fn wait_for_input_with_keymap<'a, T: Clone>(
    stdin: &mut std::io::Stdin,
    items: &'a Vec<SentakuItem<T>>,
    keymap: &HashMap<Key, SentakuAction<'a, T>>,
) -> Result<T, SentakuError> {
    if items.is_empty() {
        return Err(SentakuError::EmptyList);
    }
    let mut stdout = std::io::stdout().into_raw_mode()?;
    let mut pos = 0;
    write!(stdout, "{}", cursor::Hide)?;
    display_items(&mut stdout, items, pos)?;
    let mut canceled = false;
    for c in stdin.keys() {
        let action = keymap.get(&c.unwrap());
        match action {
            Some(SentakuAction::Down) => {
                pos = std::cmp::min(pos + 1, items.len() - 1);
            },
            Some(SentakuAction::Up) => {
                pos = std::cmp::max(1, pos) - 1;
            },
            Some(SentakuAction::Select) => {
                break;
            },
            Some(SentakuAction::Cancel) => {
                canceled = true;
                break;
            },
            Some(SentakuAction::Action(f)) => {
                f(&items[pos].value);
            }
            _ => {}
        }
        write!(stdout, "{}{}", cursor::Up(items.len() as u16), clear::AfterCursor)?;
        display_items(&mut stdout, items, pos)?;
    }

    write!(stdout, "{}", cursor::Show)?;
    stdout.flush().unwrap();
    if canceled {
        Err(SentakuError::Canceled)
    } else {
        Ok(items[pos].value.clone())
    }

}

/// Wait for user input and return an item user selects with default keymap.
/// See also `default_keymap`
pub fn wait_for_input<T: Clone>(stdin: &mut std::io::Stdin, items: &Vec<SentakuItem<T>>) -> Result<T, SentakuError> {
    wait_for_input_with_keymap(stdin, items, &get_default_keymap())
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}