summaryrefslogtreecommitdiffstats
path: root/src/ui/widgets/tui_textfield.rs
blob: 3ca7ad9c0303c30b45cba74e698bac0b9b258037 (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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
use rustyline::completion::{Candidate, Completer, FilenameCompleter, Pair};
use rustyline::line_buffer;

use termion::event::Key;
use tui::layout::Rect;
use tui::style::{Color, Modifier, Style};
use tui::text::{Span, Spans};
use tui::widgets::{Clear, Paragraph, Wrap};

use crate::context::JoshutoContext;
use crate::ui::TuiBackend;
use crate::util::event::Event;
use crate::util::worker;

use super::{TuiMenu, TuiView};

struct CompletionTracker {
    pub index: usize,
    pub pos: usize,
    pub original: String,
    pub candidates: Vec<Pair>,
}

impl CompletionTracker {
    pub fn new(pos: usize, candidates: Vec<Pair>, original: String) -> Self {
        CompletionTracker {
            index: 0,
            pos,
            original,
            candidates,
        }
    }
}

pub struct TuiTextField<'a> {
    _prompt: &'a str,
    _prefix: &'a str,
    _suffix: &'a str,
    _menu_items: Option<Vec<&'a str>>,
}

impl<'a> TuiTextField<'a> {
    pub fn menu_items<I>(&mut self, items: I) -> &mut Self
        where I: Iterator<Item = &'a str> {
        self._menu_items = Some(items.collect());
        self
    }

    pub fn prompt(&mut self, prompt: &'a str) -> &mut Self {
        self._prompt = prompt;
        self
    }

    pub fn prefix(&mut self, prefix: &'a str) -> &mut Self {
        self._prefix = prefix;
        self
    }

    pub fn suffix(&mut self, suffix: &'a str) -> &mut Self {
        self._suffix = suffix;
        self
    }

    pub fn get_input(
        &mut self,
        backend: &mut TuiBackend,
        context: &mut JoshutoContext,
    ) -> Option<String> {
        context.flush_event();

        let mut line_buffer = line_buffer::LineBuffer::with_capacity(255);
        let completer = FilenameCompleter::new();

        let mut completion_tracker: Option<CompletionTracker> = None;

        let char_idx = self._prefix.chars().map(|c| c.len_utf8()).sum();

        line_buffer.insert_str(0, self._suffix);
        line_buffer.insert_str(0, self._prefix);
        line_buffer.set_pos(char_idx);

        let terminal = backend.terminal_mut();

        loop {
            terminal
                .draw(|frame| {
                    let f_size: Rect = frame.size();
                    if f_size.height == 0 {
                        return;
                    }

                    {
                        let mut view = TuiView::new(&context);
                        view.show_bottom_status = false;
                        frame.render_widget(view, f_size);
                    }

                    if let Some(items) = self._menu_items.as_ref() {
                        let menu_len = items.len();
                        let menu_y = if menu_len + 2 > f_size.height as usize {
                            0
                        } else {
                            (f_size.height as usize - menu_len - 2) as u16
                        };

                        let rect = Rect {
                            x: 0,
                            y: menu_y,
                            width: f_size.width,
                            height: menu_len as u16,
                        };
                        let menu_widget = TuiMenu::new(items);
                        frame.render_widget(menu_widget, rect);
                    }

                    let cursor_xpos = line_buffer.pos();

                    let prefix = &line_buffer.as_str()[..cursor_xpos];

                    let curr = line_buffer.as_str()[cursor_xpos..].chars().next();
                    let (suffix, curr) = match curr {
                        Some(c) => {
                            let curr_len = c.len_utf8();
                            (&line_buffer.as_str()[(cursor_xpos + curr_len)..], c)
                        }
                        None => ("", ' '),
                    };

                    let cmd_prompt_style = Style::default().fg(Color::LightGreen);
                    let cursor_style = Style::default().add_modifier(Modifier::REVERSED);
                    let default_style = Style::default().fg(Color::Reset).bg(Color::Reset);

                    let curr_string = curr.to_string();

                    let text = Spans::from(vec![
                        Span::styled(self._prompt, cmd_prompt_style),
                        Span::styled(prefix, default_style),
                        Span::styled(curr_string, cursor_style),
                        Span::styled(suffix, default_style),
                        Span::styled(" ", default_style),
                        Span::styled(".", Style::default().fg(Color::Black).bg(Color::Reset)),
                    ]);

                    let textfield_rect = Rect {
                        x: 0,
                        y: f_size.height - 1,
                        width: f_size.width,
                        height: 1,
                    };

                    frame.render_widget(Clear, textfield_rect);
                    frame.render_widget(
                        Paragraph::new(text).wrap(Wrap { trim: true }),
                        textfield_rect,
                    );
                })
                .unwrap();

            if let Ok(event) = context.poll_event() {
                match event {
                    Event::IOWorkerProgress(res) => {
                        worker::process_worker_progress(context, res);
                    }
                    Event::IOWorkerResult(res) => {
                        worker::process_finished_worker(context, res);
                    }
                    Event::Input(key) => {
                        match key {
                            Key::Backspace => {
                                if line_buffer.backspace(1) {
                                    completion_tracker.take();
                                }
                            }
                            Key::Left => {
                                if line_buffer.move_backward(1) {
                                    completion_tracker.take();
                                }
                            }
                            Key::Right => {
                                if line_buffer.move_forward(1) {
                                    completion_tracker.take();
                                }
                            }
                            Key::Delete => {
                                if line_buffer.delete(1).is_some() {
                                    completion_tracker.take();
                                }
                            }
                            Key::Home => {
                                line_buffer.move_home();
                                completion_tracker.take();
                            }
                            Key::End => {
                                line_buffer.move_end();
                                completion_tracker.take();
                            }
                            Key::Up => {}
                            Key::Down => {}
                            Key::Esc => {
                                return None;
                            }
                            Key::Char('\t') => {
                                if completion_tracker.is_none() {
                                    let res = completer
                                        .complete_path(line_buffer.as_str(), line_buffer.pos());
                                    if let Ok((pos, mut candidates)) = res {
                                        candidates.sort_by(|x, y| {
                                            x.display()
                                                .partial_cmp(y.display())
                                                .unwrap_or(std::cmp::Ordering::Less)
                                        });
                                        let ct = CompletionTracker::new(
                                            pos,
                                            candidates,
                                            String::from(line_buffer.as_str()),
                                        );
                                        completion_tracker = Some(ct);
                                    }
                                }

                                if let Some(ref mut s) = completion_tracker {
                                    if s.index < s.candidates.len() {
                                        let candidate = &s.candidates[s.index];
                                        completer.update(
                                            &mut line_buffer,
                                            s.pos,
                                            candidate.display(),
                                        );
                                        s.index += 1;
                                    }
                                }
                            }
                            Key::Char('\n') => {
                                break;
                            }
                            Key::Char(c) => {
                                if line_buffer.insert(c, 1).is_some() {