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
use std::io::{self, Write, BufWriter};

use super::{MatchWithPositions, match_and_score_with_positions};
use ansi::{clear, color, cursor, style};
use terminal::{self, Terminal, Key, Event};

use rayon::prelude::*;

#[derive(Debug)]
pub enum Error {
    Exit,
    Write(io::Error),
    Reset(terminal::Error)
}

impl From<io::Error> for Error {
    fn from(err: io::Error) -> Error {
        Error::Write(err)
    }
}

impl From<terminal::Error> for Error {
    fn from(err: terminal::Error) -> Error {
        Error::Reset(err)
    }
}

pub struct Interface<'a> {
    lines: &'a [String],
    matches: Vec<MatchWithPositions<'a>>,

    search: String,
    selected: usize,

    choices_width: usize,
    width: usize,

    terminal: Terminal,
}

impl<'a> Interface<'a> {
    // Creates a new Interface with the provided lines
    pub fn new(lines: &'a [String]) -> Interface<'a> {
        let mut terminal = Terminal::from("/dev/tty").unwrap();
        let choices_width = format!("{}", lines.len()).len();

        terminal.set_raw_mode().unwrap();

        Interface {
            lines: lines,
            matches: vec![],
            search: String::new(),
            selected: 0,
            choices_width: choices_width,
            width: terminal.max_width,
            terminal: terminal,
        }
    }

    // Runs the Interface, returning either the final selection, or an error
    pub fn run(&mut self) -> Result<&str, Error> {
        self.filter_matches();
        self.render()?;

        for event in self.terminal.events()? {
            if let Event::Key(key) = event? {
                match key {
                    Key::Ctrl('c') | Key::Ctrl('d') | Key::Escape => {
                        self.reset()?;
                        return Err(Error::Exit);
                    }

                    Key::Char('\n') => {
                        break;
                    },

                    Key::Ctrl('n') => {
                        self.selected += 1;
                        self.render()?;
                    },

                    Key::Ctrl('p') => {
                        self.selected = self.selected.saturating_sub(1);
                        self.render()?;
                    },

                    Key::Char(ch) => {
                        self.search.push(ch);
                        self.filter_existing();
                        self.render()?;
                    },

                    Key::Backspace | Key::Ctrl('h') => {
                        self.search.pop();
                        self.filter_matches();
                        self.render()?;
                    }

                    Key::Ctrl('u') => {
                        self.search.clear();
                        self.filter_matches();
                        self.render()?;
                    }

                    _ => {}
                }
            };
        }

        self.reset()?;
        Ok(self.result())
    }

    // Matches and scores `lines` by `search`, sorting the result
    fn filter_matches(&mut self) {
        let ref search = self.search;

        self.matches = self.lines.
            par_iter().
            filter_map(|line| match_and_score_with_positions(search, line)).
            collect();

        self.matches.par_sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap().reverse());
    }

    // Matches and scores the existing `matches` by `search`, sorting the result
    fn filter_existing(&mut self) {
        let ref search = self.search;

        self.matches = self.matches.
            par_iter().
            filter_map(|&(line, _, _)| match_and_score_with_positions(search, line)).
            collect();

        self.matches.par_sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap().reverse());
    }

    // Renders the current state of the Interface to it's `terminal`
    fn render(&mut self) -> io::Result<()> {
        self.clamp_selected();

        let prompt = self.prompt();
        let matches = self.matches.iter().take(10);
        let n = matches.len() as u16;

        let mut term = BufWriter::new(&mut self.terminal);

        write!(term, "{}{}{}", cursor::Column(1), clear::Screen, prompt)?;

        for (i, choice) in matches.enumerate() {
            let selected = i == self.selected;
            let chars = choice.0.chars().take(self.width);

            write!(term, "\r\n")?;

            if selected {
                write!(term, "{}", style::Invert)?;
            }

            let ref positions = choice.2;

            for (i, ch) in chars.enumerate() {
                if positions.contains(&i) {
                    let color = color::Fg(color::Colors::Magenta);
                    let reset = color::Fg(color::Reset);
                    write!(term, "{}{}{}", color, ch, reset)?;
                } else {
                    write!(term, "{}", ch)?;
                }
            }

            if selected {
                write!(term, "{}", style::NoInvert)?;
            }
        }

        if n > 0 {
            let col = (prompt.len() + 1) as u16;
            write!(term, "{}{}", cursor::Up(n), cursor::Column(col))?;
        }

        Ok(())
    }

    // Generates the input prompt
    fn prompt(&self) -> String {
        let count = self.matches.len();
        format!("{:width$} > {}", count, self.search, width = self.choices_width)
    }

    // Clamps `selected`, such that it doesn't overflow the matches length
    fn clamp_selected(&mut self) {
        let mut max = self.matches.len();
        if max > 10 { max = 10; }

        if self.selected >= max {
            self.selected = if max > 0 { max - 1 } else { 0 };
        }
    }

    // Resets the `terminal`
    fn reset(&mut self) -> Result<(), Error> {
        write!(self.terminal, "{}{}", cursor::Column(1), clear::Screen)?;
        self.terminal.reset()?;
        Ok(())
    }

    fn result(&mut self) -> &str {
        self.matches.iter().
            nth(self.selected).
            map(|choice| choice.0).
            unwrap_or(&self.search)
    }
}