summaryrefslogtreecommitdiffstats
path: root/src/buffer.rs
blob: 366f20a3b19c96eb6ed15736689e83cb737e1536 (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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
use std::env::current_dir;
use std::fs;
use std::io::{self, Read, Write};
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

// STDIN is file descriptor (fd) 0 on Linux and other UN*X-likes
pub const STDIN: i32 = 0;

// Key input types from the user
#[derive(PartialEq)]
enum Key {
    Up,
    Down,
    Right,
    Left,
    Tab,
    ShiftTab,
    Ctrlc,
    Else(u8),
    Ignored,
}

/// Retrieve a single byte of input
///
/// Requires some setup beforehand (see beginning of repl())
fn getchar() -> Key {
    let mut b = [0; 1];
    io::stdout().lock().flush().unwrap();
    io::stdin().read_exact(&mut b).unwrap();

    // Might me an ASNI escape sequence
    match b[0] {
        // Escape sequences
        27 => {
            io::stdin().read_exact(&mut b).unwrap();

            if b[0] == 91 {
                io::stdin().read_exact(&mut b).unwrap();

                match b[0] {
                    // Arrow keys
                    65 => return Key::Up,
                    66 => return Key::Down,
                    67 => return Key::Right,
                    68 => return Key::Left,

                    // Shift tab
                    90 => return Key::ShiftTab,

                    // Everything else
                    _ => return Key::Ignored,
                }
            }

            return Key::Ignored;
        }

        // Tab
        9 => return Key::Tab,

        // ctrlc
        3 => return Key::Ctrlc,

        // Everything else
        _ => Key::Else(b[0]),
    }
}

/// Handles autocomplete functionality for file paths
///
/// Currently, dwvsh does not implement zsh's full autocomplete
/// ecosystem (though there are plans to). For now, this simply adds a
/// builtin way to get autocomplete suggestions for file paths via the
/// <tab> key.
fn autocomplete(
    buffer: &mut Arc<Mutex<Vec<u8>>>,
    index: usize,
    pwd: &PathBuf,
) -> Result<(String, usize), Box<dyn std::error::Error>> {
    let buffer = buffer.lock().unwrap();
    let word = match buffer.last() {
        Some(c) if *c == b' ' => "".to_string(),
        None => "".to_string(),
        _ => {
            let mut word: Vec<u8> = vec![];
            for c in buffer.iter().rev() {
                if *c == b' ' || *c == b'/' {
                    break;
                }
                word.push(*c);
            }
            word.reverse();
            String::from_utf8_lossy(&mut word).to_string()
        }
    };

    // Get a file listing
    let paths = fs::read_dir(&pwd)?;
    let paths = if word.is_empty() {
        paths
            .into_iter()
            .filter(|path| {
                !path
                    .as_ref()
                    .unwrap()
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".")
            })
            .collect::<Vec<_>>()
    } else {
        paths
            .into_iter()
            .filter(|path| {
                path.as_ref()
                    .unwrap()
                    .file_name()
                    .to_string_lossy()
                    .starts_with(&word)
            })
            .collect::<Vec<_>>()
    };

    // Return nothing is paths is empty
    if paths.is_empty() {
        return Ok(("".to_string(), 0));
    }

    // Collect path into DirEntries
    let mut paths = paths
        .iter()
        .map(|path| path.as_ref().unwrap())
        .collect::<Vec<_>>();

    // Sort the paths
    paths.sort_by(|a, b| {
        a.file_name()
            .to_ascii_lowercase()
            .cmp(&b.file_name().to_ascii_lowercase())
    });

    // Output the file listing at index on the prompt
    // let path = paths[index].path();
    let path = paths[index].path();

    let path = if path.is_dir() {
        path.file_name().unwrap().to_str().unwrap().to_string() + "/"
    } else {
        path.file_name().unwrap().to_str().unwrap().to_string()
    };

    let path = if word.is_empty() {
        path
    } else {
        path[word.len()..].to_string()
    };

    print!("{}", path);

    Ok((path, paths.len()))
}

/// Handle user input at the repl prompt
///
/// This is required instead of io::stdin().read_line(), because certain
/// keys like `<tab>` and `<up>` have special functions (cycle through
/// autocomplete options, and history, respectively). It leverages
/// [getchar] to read each character as the user inputs it. This also
/// means special cases for handling backspace, newlines, etc. Assumes
/// that (ICANON and ECHO) are off. See the beginning of [crate::repl]
/// for more details.
pub fn getline(buffer: &mut Arc<Mutex<Vec<u8>>>, pos: &mut Arc<Mutex<usize>>) -> usize {
    // Keep track of the last key
    let mut last: Option<Key> = None;

    // Keep track of index for autocomplete
    let mut pwd = current_dir().unwrap_or(PathBuf::from(env!("HOME")));
    let mut auindex = 0;
    let mut aulen = 0;

    // Keep track of the length of the last buffer from autcomplete()
    let mut length = 0;

    // Loop over characters until there is a newline
    loop {
        let c = getchar();
        match c {
            Key::Up => {
                continue;
            }
            Key::Down => {
                continue;
            }
            Key::Right => {
                if *pos.lock().unwrap() >= buffer.lock().unwrap().len() {
                    continue;
                }
                print!("\x1b[1C");
                *pos.lock().unwrap() += 1;
            }
            Key::Left => {
                if *pos.lock().unwrap() == 0 {
                    continue;
                }
                print!("\u{8}");
                *pos.lock().unwrap() -= 1;
            }
            Key::Tab => {
                if last == Some(Key::ShiftTab) {
                    auindex += 2;
                    if auindex >= length {
                        auindex = 0;
                    }
                }
                while aulen > 0 {
                    buffer.lock().unwrap().pop();
                    print!("\u{8} \u{8}");
                    *pos.lock().unwrap() -= 1;
                    aulen -= 1;
                }
                let (path, len) =
                    autocomplete(buffer, auindex, &pwd).unwrap_or(("".to_string(), 0));
                length = len;
                for c in path.into_bytes().iter() {
                    buffer.lock().unwrap().insert(*pos.lock().unwrap(), *c);
                    *pos.lock().unwrap() += 1;
                    aulen += 1;
                }
                auindex += 1;
                if auindex >= len {
                    auindex = 0;
                }
            }
            Key::ShiftTab => {
                if last == Some(Key::Tab) {
                    if auindex.checked_sub(2) == None {
                        auindex = length - 1;
                    } else {
                        auindex -= 2;
                    }
                }
                while aulen > 0 {
                    buffer.lock().unwrap().pop();
                    print!("\u{8} \u{8}");
                    *pos.lock().unwrap() -= 1;
                    aulen -= 1;
                }
                let (path, len) =
                    autocomplete(buffer, auindex, &pwd).unwrap_or(("".to_string(), 0));
                length = len;
                for c in path.into_bytes().iter() {
                    buffer.lock().unwrap().insert(*pos.lock().unwrap(), *c);
                    *pos.lock().unwrap() += 1;
                    aulen += 1;
                }
                auindex = if auindex == 0 { len - 1 } else { auindex - 1 };
            }
            Key::Ctrlc => {
                kill(Pid::from_raw(0 as i32), Signal::SIGINT).unwrap();
            }
            Key::Ignored => {
                continue;
            }
            Key::Else(c) => match c {
                // enter/return
                b'\n' => break,

                // tab
                b'\t' => {
                    *pos.lock().unwrap() += 1;
                    print!(" ");
                    buffer.lock().unwrap().push(b' ');
                }

                // ctrl-d
                4 => return 0,

                // backspace
                127 => {
                    if *pos.lock().unwrap() == 0 {
                        continue;
                    }
                    *pos.lock().unwrap() -= 1;

                    if *pos.lock().unwrap() == buffer.lock().unwrap().len() {
                        buffer.lock().unwrap().pop();
                        print!("\u{8} \u{8}");
                    } else {
                        buffer.lock().unwrap().remove(*pos.lock().unwrap());
                        print!(
                            "\u{8}{} ",
                            String::from_utf8_lossy(
                                &buffer.lock().unwrap()[*pos.lock().unwrap()..]
                            )
                        );
                        for _ in *pos.lock().unwrap()..buffer.lock().unwrap().len() + 1 {
                            print!("\u{8}");
                        }
                    }

                    // Reset autocomplete variables
                    auindex = 0;
                    aulen = 0;
                }

                // everything else
                _ => {
                    let mut buffer = buffer.lock().unwrap();

                    // Print out the character as the user is typing
                    match buffer.last() {
                        Some(last) if *last == b'/' && c == b'/' => {
                            buffer.pop();
                            *pos.lock().unwrap() -= 1;
                        }
                        Some(_) => print!("{}", c as char),
                        None => print!("{}", c as char),
                    }

                    // Insert the character onto the buffer at whatever *pos.lock().unwrap()ition
                    // the cursor is at
                    buffer.insert(*pos.lock().unwrap(), c);

                    // Increment our *pos.lock().unwrap()ition
                    *pos.lock().unwrap() += 1;

                    // Reprint the end of the buffer if inserting at the front or middle
                    if *pos.lock().unwrap() != buffer.len() {
                        print!(
                            "{}",
                            String::from_utf8_lossy(&buffer[*pos.lock().unwrap()..])
                        );
                        for _ in *pos.lock().unwrap()..buffer.len() {
                            print!("\u{8}");
                        }
                    }

                    // Update directory for autocomplete
                    let word = match buffer.last() {
                        Some(c) if *c == b' ' => "".to_string(),
                        None => "".to_string(),
                        _ => {
                            let mut word: Vec<u8> = vec![];
                            for c in buffer.iter().rev() {
                                if *c == b' ' {
                                    break;
                                }
                                word.push(*c);
                            }
                            word.reverse();
                            if word.starts_with(b"..")
                                && word.iter().filter(|c| *c == &b'/').count() == 1
                            {
                                word = vec![b'.', b'.']
                            }
                            loop {
                                match word.last() {
                                    Some(c) if *c == b'/' || *c == b'.' || *c == b'~' => {
                                        break;
                                    }
                                    Some(_) => {
                                        word.pop();
                                    }
                                    None => {
                                        break;
                                    }
                                }
                            }
                            String::from_utf8_lossy(&mut word).to_string()
                        }
                    };

                    // Check for the ~ character (used to represent $HOME)
                    let word = if word.is_empty() {
                        current_dir()
                            .unwrap_or(PathBuf::from(env!("HOME")))
                            .to_string_lossy()
                            .to_string()
                    } else if word.starts_with("~") {
                        let home = env!("HOME");
                        format!("{}{}", home, &word[1..]).to_string()
                    } else {
                        word
                    };

                    // Reset autocomplete variables
                    pwd = PathBuf::from(word);
                    auindex = 0;
                    aulen = 0;
                }
            },
        }

        // Update the last key
        last = Some(c);
    }

    *pos.lock().unwrap() = 0;
    println!();
    buffer.lock().unwrap().push(b'\n');
    buffer.lock().unwrap().len()
}