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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
|
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};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// Typical file descriptor for STDIN on Linux on other U**X-likes
pub const STDIN: i32 = 0;
/// Keys recognized by [getchar]
#[derive(Clone, PartialEq)]
pub enum Key {
/// Up arrow key
Up,
/// Down arrow key
Down,
/// Right arrow key
Right,
/// Left arrow key
Left,
/// Tab key
Tab,
/// Shift + Tab key combo
ShiftTab,
/// Backspace key
Backspace,
/// Return (or Enter) key
Newline,
/// Ctrl + c key combo
Ctrlc,
/// Ctrl + d key combo
Ctrld,
/// An ASCII or UTF-8 character
Else(char),
/// Key not recognized by [getchar]
Ignored,
}
/// Flush STDIN
macro_rules! flush {
() => {
io::stdout().lock().flush().unwrap();
};
}
/// Read the next (single) byte of input from STDIN
macro_rules! getc {
($buffer:expr) => {
match io::stdin().read_exact($buffer) {
Ok(_) => {}
Err(_) => return Key::Ignored,
}
};
}
/// Try to convert a UTF-8 byte sequence into a [std::char]
macro_rules! char {
($extension:expr) => {
match String::from_utf8_lossy($extension).chars().next() {
Some(c) => Key::Else(c),
None => Key::Ignored,
}
};
}
/// Retrieve the next character from STDIN
///
/// A UTF-8 compatible function used to get the next character from STDIN. A UTF-8 character may be
/// anywhere from 1 byte to 4 bytes. The function does not (yet) account for every single key (or
/// key combination) that a user might input. For any key (and/or combo) that is not recognized,
/// this returns [Key::Ignored], and is functionally treated as a no op.
///
/// Please see [Key] for a list of keys and combos that are recognized.
fn getchar() -> Key {
flush!();
let mut header = [0; 1];
let mut extension = Vec::new();
getc!(&mut header);
extension.push(header[0]);
if header[0] <= 0x7f {
match header[0] {
3 => return Key::Ctrlc,
4 => return Key::Ctrld,
9 => return Key::Tab,
b'\n' => return Key::Newline,
127 => return Key::Backspace,
_ => {}
}
if header[0] == 27 {
getc!(&mut header);
match header[0] {
91 => {
getc!(&mut header);
match header[0] {
65 => return Key::Up,
66 => return Key::Down,
67 => return Key::Right,
68 => return Key::Left,
90 => return Key::ShiftTab,
_ => return Key::Ignored,
}
}
_ => return Key::Ignored,
}
}
char!(&extension)
} else if header[0] >= 0xc0 && header[0] <= 0xdf {
let mut continuation = [0; 1];
getc!(&mut continuation);
extension.extend(continuation);
char!(&extension)
} else if header[0] >= 0xe0 && header[0] <= 0xef {
let mut continuation = [0; 2];
getc!(&mut continuation);
extension.extend(continuation);
char!(&extension)
} else if header[0] >= 0xf0 && header[0] <= 0xf7 {
let mut continuation = [0; 3];
getc!(&mut continuation);
extension.extend(continuation);
char!(&extension)
} else {
Key::Ignored
}
}
/// Typical (tab drivem) completion
///
/// This function provides a primitive form of shell completion (tab autocomplete). Currently, it
/// only works with file paths, there is NO completion for commands, for instance. Also, completion
/// is only enabled if the cursor is at the end of the buffer. Otherwise, pressing Tab will have no
/// effect.
///
/// This function cycles through possible completion paths, keeping track of the position, present
/// working directory, etc.
fn comp(
buffer: &mut Vec<char>,
bpos: &mut usize,
pos: &mut usize,
len: &mut usize,
pwd: &mut PathBuf,
last_key: Key,
reverse: bool,
) -> String {
// Reset the buffer position
if *bpos >= *len {
*bpos -= *len;
}
let ori_path: String = buffer[*bpos..].into_iter().collect::<String>();
let mut width = UnicodeWidthStr::width(ori_path.as_str());
// Remove the last autocomplete value from the buffer
while *len > 0 {
buffer.pop();
*len -= 1;
}
// Remove the last autocomplete value from the shell
while width > 0 {
print!("\u{8} \u{8}");
width -= 1;
}
// Reverse the buffer, which will make our while loop further down much easier
let mut rev = buffer.iter().rev();
// Holds the last word (i.e. anything after the last space (' ') or forward slash ('/'))
let mut word = Vec::new();
while let Some(c) = rev.next() {
match rev.clone().peekable().peek() {
Some(next) if **next == '\\' => {
word.push(*c);
}
Some(_) => {
if *c == ' ' || *c == '/' {
break;
}
word.push(*c);
}
None => {
word.push(*c);
break;
}
}
}
// Collect the word into a String
let word = word
.iter()
.rev()
.filter(|c| **c != '\\')
.collect::<String>();
// Get a file listing, filtering for the word, if it is not empty
let paths = match fs::read_dir(pwd) {
Ok(paths) => paths,
Err(_) => return String::new(),
};
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 if there are not matches
if paths.is_empty() {
return String::new();
}
// Collect path into DirEntry(s)
let mut paths = paths
.iter()
.map(|path| path.as_ref().unwrap())
.collect::<Vec<_>>();
// Sort the entries in alphabetical order
paths.sort_by(|a, b| {
a.file_name()
.to_ascii_lowercase()
.cmp(&b.file_name().to_ascii_lowercase())
});
// Do extra maths on the position if switching autocomplete directions
if last_key == Key::Tab && reverse {
let ori_pos = *pos;
if *pos == 0 || *pos == 1 {
*pos = paths.len();
}
if ori_pos == 1 {
*pos -= 1;
} else {
*pos -= 2;
}
}
// Do extra maths on the position if switching autocomplete directions
if last_key == Key::ShiftTab && !reverse {
if *pos == 0 {
*pos = paths.len();
}
*pos += 2;
}
// Reset the position if it's larger than the number of entries
if *pos >= paths.len() {
*pos = *pos - paths.len();
// Need to double-check the newly computed pos
if *pos >= paths.len() {
*pos = 0;
}
}
// Get the path (or only part of the path if we matched with word)
let path = paths[*pos].path();
let path = if paths[*pos].path().is_dir() {
(path.file_name().unwrap().to_string_lossy()[word.len()..].to_string() + "/").to_string()
} else {
path.file_name().unwrap().to_string_lossy()[word.len()..].to_string()
};
// Reset from previous autocomplete
(0..*len).for_each(|_| print!("\u{8}"));
(0..*len).for_each(|_| print!(" "));
(0..*len).for_each(|_| print!("\u{8}"));
let mut j = 0;
let mut chars = path.chars().collect::<Vec<char>>();
for (i, c) in chars.clone().iter().enumerate() {
if *c == ' ' {
chars.insert(i + j, '\\');
j += 1;
}
}
let path = chars.iter().collect::<String>();
// Print out the path
print!("{}", path);
// Update the buffer
buffer.append(&mut path.chars().collect::<Vec<_>>());
// Math the position
if reverse {
if *pos == 0 {
*pos = paths.len();
}
*pos -= 1;
} else {
*pos += 1;
}
// Update the length of the last comp
*len += path.chars().collect::<Vec<_>>().len();
// Update the buffer position
*bpos += *len;
path
}
pub fn getline(
buffer: &mut Arc<Mutex<Vec<char>>>,
pos: &mut Arc<Mutex<usize>>,
comp_pos: &mut Arc<Mutex<usize>>,
comp_len: &mut Arc<Mutex<usize>>,
last_key: &mut Arc<Mutex<Key>>,
) -> usize {
// Position in the buffer. Subject to change based on input from the user. Typing a character
// increments the position, while backspacing will decrement it. The user may also move it
// manually using the arrow keys to insert or delete at an arbitrary location in the buffer.
// let mut pos = 0;
// Present working directory. Keeps track of the user's PWD for autocomplete.
let mut pwd = current_dir().unwrap_or(PathBuf::from("."));
// Position in the autocomplete list. This value gets reset if a new autocomplete list is
// generated (for instance, if the user presses '/' to start autocomplete in a new directory).
// let mut comp_pos = 0;
// Keep track of the length of the last buffer from comp().
// let mut comp_len = 0;
// Keep track of the last key for autocomplete, as we may need to add or sub additionally from
// comp_pos before calling comp().
// let mut last_key = Key::Ignored;
// Always clear our state variables before proceeding
buffer.lock().unwrap().clear();
*pos.lock().unwrap() = 0;
*comp_pos.lock().unwrap() = 0;
*comp_len.lock().unwrap() = 0;
*last_key.lock().unwrap() = Key::Ignored;
// Receive input
loop {
match getchar() {
Key::Tab => {
if *pos.lock().unwrap() != buffer.lock().unwrap().len() {
continue;
}
comp(
&mut buffer.lock().unwrap(),
&mut pos.lock().unwrap(),
&mut comp_pos.lock().unwrap(),
&mut comp_len.lock().unwrap(),
&mut pwd,
last_key.lock().unwrap().clone(),
false,
);
*last_key.lock().unwrap() = Key::Tab;
}
Key::ShiftTab => {
if *pos.lock().unwrap() != buffer.lock().unwrap().len() {
continue;
}
comp(
&mut buffer.lock().unwrap(),
&mut pos.lock().unwrap(),
&mut comp_pos.lock().unwrap(),
&mut comp_len.lock().unwrap(),
&mut pwd,
last_key.lock().unwrap().clone(),
true,
);
*last_key.lock().unwrap() = Key::ShiftTab;
}
Key::Ctrlc => kill(Pid::from_raw(0 as i32), Signal::SIGINT).unwrap(),
Key::Ctrld => return 0,
Key::Backspace => {
if *pos.lock().unwrap() == 0 {
continue;
}
*pos.lock().unwrap() -= 1;
let trunc = &buffer.lock().unwrap()[*pos.lock().unwrap()..]
.iter()
.collect::<String>();
let trunc_width = UnicodeWidthStr::width(trunc.as_str());
let c = buffer.lock().unwrap().remove(*pos.lock().unwrap());
let width = UnicodeWidthChar::width(c).unwrap_or(1);
if *pos.lock().unwrap() == buffer.lock().unwrap().len() {
(0..width).for_each(|_| print!("\u{8}"));
print!(" \u{8}");
} else {
(0..trunc_width).for_each(|_| print!(" "));
(0..trunc_width + width).for_each(|_| print!("\u{8}"));
buffer.lock().unwrap()[*pos.lock().unwrap()..]
.iter()
.for_each(|c| print!("{}", c));
(0..trunc_width - width).for_each(|_| print!("\u{8}"));
}
// Update directory for autocomplete
let buffer = buffer.lock().unwrap();
let comp_path = match buffer.last() {
Some(c) if *c == ' ' => String::new(),
None => String::new(),
_ => {
let mut path = Vec::new();
for c in buffer.iter().rev() {
if *c == ' ' {
break;
}
path.push(*c);
}
let mut path = path.iter().rev().collect::<String>();
if path.starts_with("..") && path.chars().filter(|c| *c == '/').count() == 1
{
path = String::from("..");
}
loop {
match path.chars().last() {
Some(c) if c == '/' || c == '.' || c == '~' => {
break;
}
Some(_) => {
path.pop();
}
None => {
break;
}
}
}
path
}
};
// Reset comp variables
pwd = if comp_path.is_empty() {
current_dir().unwrap_or(PathBuf::from("."))
} else if comp_path.starts_with("~") {
PathBuf::from(format!("{}{}", env!("HOME"), &comp_path[1..]).to_string())
} else {
PathBuf::from(comp_path)
};
*comp_pos.lock().unwrap() = 0;
let mut comp_len = comp_len.lock().unwrap();
if *comp_len > 0 {
*comp_len -= 1;
}
}
Key::Up => continue,
Key::Down => continue,
Key::Right => {
if *pos.lock().unwrap() >= buffer.lock().unwrap().len() {
continue;
}
let width = UnicodeWidthChar::width(buffer.lock().unwrap()[*pos.lock().unwrap()])
.unwrap_or(1);
for _ in 0..width {
print!("\x1b[1C");
}
*pos.lock().unwrap() += 1;
}
Key::Left => {
if *pos.lock().unwrap() == 0 {
continue;
}
*pos.lock().unwrap() -= 1;
let width = UnicodeWidthChar::width(buffer.lock().unwrap()[*pos.lock().unwrap()])
.unwrap_or(1);
for _ in 0..width {
print!("\u{8}");
}
}
Key::Ignored => continue,
Key::Newline => break,
Key::Else(c) => {
let mut buffer = buffer.lock().unwrap();
match buffer.last() {
Some(last) if *last == '/' && c == '/' => {
buffer.pop();
*pos.lock().unwrap() -= 1;
print!("\u{8} \u{8}")
}
_ => {}
}
let trunc = &buffer[*pos.lock().unwrap()..].iter().collect::<String>();
let trunc_width = UnicodeWidthStr::width(trunc.as_str());
buffer.insert(*pos.lock().unwrap(), c);
*pos.lock().unwrap() += 1;
// *pos.lock().unwrap() += UnicodeWidthChar::width(c).unwrap_or(1);
if *pos.lock().unwrap() == buffer.len() {
print!("{}", c);
} else {
(0..trunc_width).for_each(|_| print!(" "));
(0..trunc_width).for_each(|_| print!("\u{8}"));
buffer[*pos.lock().unwrap() - 1..]
.iter()
.for_each(|c| print!("{}", c));
(0..trunc_width).for_each(|_| print!("\u{8}"));
}
// Update directory for autocomplete
let comp_path = match buffer.last() {
Some(c) if *c == ' ' => String::new(),
None => String::new(),
_ => {
let mut path = Vec::new();
for c in buffer.iter().rev() {
if *c == ' ' {
break;
}
path.push(*c);
}
let mut path = path.iter().rev().collect::<String>();
if path.starts_with("..") && path.chars().filter(|c| *c == '/').count() == 1
{
path = String::from("..");
}
loop {
match path.chars().last() {
Some(c) if c == '/' || c == '.' || c == '~' => {
break;
}
Some(_) => {
path.pop();
}
None => {
break;
}
}
}
path
}
};
// Reset comp variables
pwd = if comp_path.is_empty() {
current_dir().unwrap_or(PathBuf::from("."))
} else if comp_path.starts_with("~") {
PathBuf::from(format!("{}{}", env!("HOME"), &comp_path[1..]).to_string())
} else {
PathBuf::from(comp_path)
};
*comp_pos.lock().unwrap() = 0;
*comp_len.lock().unwrap() = 0;
}
};
}
println!();
buffer.lock().unwrap().push('\n');
let mut bytes = 0;
buffer
.lock()
.unwrap()
.iter()
.for_each(|c| bytes += c.len_utf8());
bytes
}
|