summaryrefslogtreecommitdiffstats
path: root/src/minibuffer.rs
blob: 25330145b097b90de64fa024cdc8dd1fbf6e64e8 (plain)
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
use termion::event::Key;
use std::io::{stdout, Write};

use crate::coordinates::{Coordinates};
use crate::widget::Widget;
use crate::fail::{HResult, HError};
use crate::term;

pub struct MiniBuffer {
    coordinates: Coordinates,
    query: String,
    input: String,
    done: bool,
    position: usize,
    history: Vec<String>
}

impl MiniBuffer {
    pub fn new() -> MiniBuffer {
        let xsize = crate::term::xsize();
        let ysize = crate::term::ysize();
        let coordinates = Coordinates::new_at(xsize, 1, 1, ysize);
        MiniBuffer {
            coordinates: coordinates,
            query: String::new(),
            input: String::new(),
            done: false,
            position: 0,
            history: vec![]
        }
    }

    pub fn query(&mut self, query: &str) -> HResult<String> {
        self.query = query.to_string();
        self.input.clear();
        self.done = false;
        self.position = 0;

        write!(stdout(), "{}", termion::cursor::Show)?;

        self.popup()?;


        // for event in stdin().events() {
        //     let event = event?;
        //     self.on_event(event);
        //     if self.done {
        //         break
        //     }
        //     self.draw()?;

        //     write!(stdout(), "{}", termion::cursor::Restore)?;
        //     if self.position != 0 {
        //         write!(stdout(),
        //                "{}",
        //                termion::cursor::Right(self.position as u16))?;
        //     }
        //     stdout().flush()?;
        // }

        Ok(self.input.clone())
    }

    pub fn input_finnished(&mut self) -> HResult<()> {
        return Err(HError::PopupFinnished)
    }
}

pub fn find_bins(comp_name: &str) -> Vec<String> {
    let paths = std::env::var_os("PATH").unwrap()
        .to_string_lossy()
        .split(":")
        .map(|s| s.to_string())
        .collect::<Vec<String>>();

    paths.iter().map(|path| {
        std::fs::read_dir(path).unwrap().flat_map(|file| {
            let file = file.unwrap();
            let name = file.file_name().into_string().unwrap();
            if name.starts_with(comp_name) {
                Some(name)
            } else {
                None
            }
        }).collect::<Vec<String>>()
    }).flatten().collect::<Vec<String>>()
}

pub fn find_files(mut comp_name: String) -> Vec<String> {
    let mut path = std::path::PathBuf::from(&comp_name);

    let dir = if comp_name.starts_with("/") {
        comp_name = path.file_name().unwrap().to_string_lossy().to_string();
        path.pop();
        path.to_string_lossy().to_string()
    } else {
        std::env::current_dir().unwrap().to_string_lossy().to_string()
    };

    let reader = std::fs::read_dir(dir.clone());
    if reader.is_err() { return vec![]  }
    let reader = reader.unwrap();

    reader.flat_map(|file| {
        let file = file.unwrap();
        let name = file.file_name().into_string().unwrap();
        if name.starts_with(&comp_name) {
            if file.file_type().unwrap().is_dir() {
                Some(format!("{}/{}/", &dir, name))
            } else {
                Some(format!("/{}/", name))
            }
        } else {
            None
        }
    }).collect::<Vec<String>>()
}

impl Widget for MiniBuffer {
    fn get_coordinates(&self) -> &Coordinates {
        &self.coordinates
    }
    fn set_coordinates(&mut self, coordinates: &Coordinates) {
        self.coordinates = coordinates.clone();
        self.refresh();
    }
    fn render_header(&self) -> String {
        "".to_string()
    }
    fn refresh(&mut self) {
    }

    fn get_drawlist(&self) -> String {
        let (xpos, ypos) = self.get_coordinates().u16position();
        format!("{}{}{}: {}",
                crate::term::goto_xy(xpos, ypos),
                termion::clear::CurrentLine,
                self.query,
                self.input)
    }

    fn on_key(&mut self, key: Key) -> HResult<()> {
        match key {
            Key::Esc | Key::Ctrl('c') => { self.input_finnished()?; },
            Key::Char('\n') => {
                if self.input != "" {
                    self.history.push(self.input.clone());
                }
                self.input_finnished()?;
            }
            Key::Char('\t') => {
                if !self.input.ends_with(" ") {
                    let part = self.input.rsplitn(2, " ").take(1)
                        .map(|s| s.to_string()).collect::<String>();
                    let completions = find_files(part.clone());
                    if !completions.is_empty() {
                        self.input
                            = self.input[..self.input.len() - part.len()].to_string();
                        self.input.push_str(&completions[0]);
                        self.position += &completions[0].len() - part.len();
                    } else {
                        let completions = find_bins(&part);
                        if !completions.is_empty() {
                            self.input = self.input[..self.input.len()
                                                    - part.len()].to_string();
                            self.input.push_str(&completions[0]);
                            self.position += &completions[0].len() - part.len();
                        }
                    }
                } else {
                    self.input += "$s";
                    self.position += 2
                }
            }
            Key::Backspace => {
                if self.position != 0 {
                    self.input.remove(self.position - 1);
                    self.position -= 1;
                }
            }
            Key::Delete | Key::Ctrl('d') => {
                if self.position != self.input.len() {
                    self.input.remove(self.position);
                }
            }
            Key::Left | Key::Ctrl('b') => {
                if self.position != 0 {
                    self.position -= 1;
                }
            }
            Key::Right | Key::Ctrl('f') => {
                if self.position != self.input.len() {
                    self.position += 1;
                }
            }
            Key::Ctrl('a') => { self.position = 0 },
            Key::Ctrl('e') => { self.position = self.input.len(); },
            Key::Char(key) => {
                self.input.insert(self.position, key);
                self.position += 1;
            }
            _ => {  }
        }
        Ok(())
    }

    fn after_draw(&self) -> HResult<()> {
        let cursor_pos = self.query.len() +
                         ": ".len() +
                         self.position +
                         1;

        let ysize = term::ysize();


        write!(stdout(), "{}", term::goto_xy(cursor_pos as u16, ysize))?;
        stdout().flush()?;
        Ok(())
    }
}