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
use crate::Config;
use crate::TermBuffer;
use crossterm::{self as ct, InputEvent, KeyEvent};

#[derive(Debug)]
pub struct ScopePrompt<'a> {
    config: &'a mut Config,
    input: String,
    selected_index: u16,
    ty: &'a str,
    x_offset: u16,
    finished: bool,
}

pub enum ScopePromptResult {
    Scope(Option<String>),
    Escape,
    Terminate,
}

impl<'a> ScopePrompt<'a> {
    pub fn new(config: &'a mut Config, ty: &'a str) -> Self {
        ScopePrompt {
            config,
            input: Default::default(),
            selected_index: 0,
            ty,
            x_offset: 0,
            finished: false,
        }
    }

    pub fn run(mut self) -> ScopePromptResult {
        let mut buffer = TermBuffer::new();

        let figlet = self
            .config
            .get_figlet()
            .expect("Ensure figlet_file points to a valid file, or remove it.");

        let input = crossterm::input();
        let mut sync_stdin = input.read_sync();

        let mut first_iteration = true;

        loop {
            let event = if first_iteration {
                first_iteration = false;
                None
            } else {
                sync_stdin.next()
            };

            match event {
                Some(InputEvent::Keyboard(KeyEvent::Ctrl('c'))) => {
                    return ScopePromptResult::Terminate;
                }
                Some(InputEvent::Keyboard(KeyEvent::Char('\n'))) => {
                    self.finished = true;
                }
                Some(InputEvent::Keyboard(KeyEvent::Char(c))) => {
                    let accept = (c >= 'a' && c <= 'z')
                        || (c >= 'A' && c <= 'Z')
                        || (c >= '0' && c <= '9')
                        || (c == '_')
                        || c == '-'
                        || c == '/'
                        || c == ','
                        || c == '|';
                    if accept {
                        self.x_offset += 1;

                        self.input
                            .insert(self.x_offset as usize - 1, c.to_ascii_lowercase());
                    }
                }
                Some(InputEvent::Keyboard(KeyEvent::Left)) => {
                    self.x_offset = self.x_offset.saturating_sub(1);
                }
                Some(InputEvent::Keyboard(KeyEvent::Right)) => {
                    if (self.x_offset as usize) < self.input.len() {
                        self.x_offset += 1;
                    }
                }
                Some(InputEvent::Keyboard(KeyEvent::Backspace)) => {
                    let offset = self.x_offset as usize;
                    let len = self.input.len();
                    if len > 0 && offset < len - 1 {
                        self.input.remove(offset - 1);
                        self.x_offset -= 1;
                    } else if len > 0 {
                        self.input.pop();
                        self.x_offset -= 1;
                    }
                }
                Some(InputEvent::Keyboard(KeyEvent::Esc)) => {
                    return ScopePromptResult::Escape;
                }
                _ => {}
            };

            let (term_width, _) = ct::terminal().terminal_size();

            let mut lines = figlet.create_vec();

            let mut cursor_x = 0;
            cursor_x += figlet.write_to_buf_color(&self.ty, &mut lines[..], |s| {
                ct::style(s).with(ct::Color::Blue).to_string()
            });
            cursor_x += figlet.write_to_buf_color("(", &mut lines[..], |s| {
                ct::style(s).with(ct::Color::Grey).to_string()
            });

            let offset = self.x_offset as usize;
            cursor_x +=
                figlet.write_to_buf_color(&(self.input.as_str())[0..offset], &mut lines[..], |s| {
                    ct::style(s).with(ct::Color::Green).to_string()
                });

            let mut fig_width = cursor_x;

            // Insert the indicator for where input will be placed.
            // Note that
            if !self.finished {
                fig_width += figlet.write_to_buf_color("-", &mut lines[..], |s| {
                    ct::style(s).with(ct::Color::Grey).to_string()
                });
            }

            fig_width +=
                figlet.write_to_buf_color(&(self.input.as_str())[offset..], &mut lines[..], |s| {
                    ct::style(s).with(ct::Color::Green).to_string()
                });
            fig_width += figlet.write_to_buf_color(")", &mut lines[..], |s| {
                ct::style(s).with(ct::Color::Grey).to_string()
            });

            // We're tracking the printed width above to see if we've run out of space here.
            let figlet_overflows = fig_width + 1 > term_width as usize;

            let cursor_y = if figlet_overflows { 1 } else { 3 };

            // If we did overflow, then for now we should display it as a single line with one line of padding above/below
            if figlet_overflows {
                use std::fmt::Write;

                lines = vec!["".into(), "".into(), "".into()];
                let line = &mut lines[1];

                write!(line, "{}", ct::style(&self.ty).with(ct::Color::Blue)).unwrap();
                write!(line, "{}", ct::style("(").with(ct::Color::Grey)).unwrap();
                write!(
                    line,
                    "{}",
                    ct::style(&(self.input.as_str())[0..offset]).with(ct::Color::Green)
                )
                .unwrap();

                if !self.finished {
                    write!(line, "{}", ct::style("_").with(ct::Color::Grey)).unwrap();
                }
                write!(line, "{}", ct::style(")").with(ct::Color::Grey)).unwrap();

                cursor_x = self.ty.len() + 1 + self.input.len();
            }

            for line in lines {
                buffer.push_line(line);
            }

            buffer.set_next_cursor((cursor_x as u16, cursor_y));
            buffer.render_frame();
            buffer.flush();

            if self.finished {
                buffer.forget();
                return ScopePromptResult::Scope(Some(self.input).filter(|s| !s.is_empty()));
            }
        }
    }
}