aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib.rs
blob: 3931f5deff97c45f76c0955b09f65bce609fcedd (plain) (blame)
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
#![feature(
    unix_socket_ancillary_data,
    peer_credentials_unix_socket,
    associated_type_defaults
)]
#![allow(clippy::needless_range_loop)]

use std::collections::HashMap;
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::io::AsRawFd;
use std::path::Path;
use std::process::Command;
use std::sync::{Arc, Mutex};

pub mod ansi;
pub mod basedir;
pub mod completion;
pub mod consts;
pub mod ctrlc;
pub mod cursor;
pub mod date;
pub mod defer;
pub mod export_fun;
pub mod history;
pub mod linebuf;
pub mod panic;
pub mod parse;
pub mod raw;
pub mod reload;
pub mod run;
pub mod rw;
pub mod serialization;
pub mod wait;

use linebuf::LineBuf;
use raw::*;

use crate::completion::{PathCache, completion};
use crate::ctrlc::CtrlC;
use crate::cursor::{Direction, move_cursor};
use crate::history::HistoryEntry;
use crate::parse::{Block, ExpString, Parse, PostExpansion};

macro_rules! print {
    ($($x:tt)*) => {{
        let res = write!(io::stdout(), $($x)*);
        res.unwrap();
        io::stdout().flush().unwrap();
    }}
}

macro_rules! println {
    () => {{
        println!("")
    }};
    ($($x:tt)*) => {
        {
            let res = write!(io::stdout(), $($x)*);
            res.unwrap();
            let res = write!(io::stdout(), "\r\n");
            res.unwrap();
            io::stdout().flush().unwrap();
        }
    };
}

fn completely_clear_screen() {
    print!("\x1B[2J\x1B[1;1H");
}

fn clear_screen() {
    completely_clear_screen();
}

type BString = Vec<u8>;
#[allow(non_camel_case_types)]
type bstr = [u8];

trait PushAll {
    fn push_all(&mut self, other: &bstr);
}

impl PushAll for BString {
    fn push_all(&mut self, other: &bstr) {
        for &c in other {
            self.push(c);
        }
    }
}

pub struct Session {
    raw: Option<ScopedRawMode>,
    line: LineBuf,
    history: Vec<HistoryEntry>,
    prev_path: BString,
    builtins: HashMap<BString, &'static dyn run::BuiltinClone>,
    vars: run::Vars,
    funs: HashMap<BString, Block>,
    aliases: run::Aliases,
    socket_running: Option<export_fun::SocketRunning>,
    path_cache: PathCache,
    ctrlc: CtrlC,

    /// terminfo identifier to command invocation
    ti_keybinds: HashMap<BString, parse::Command<PostExpansion>>,
    /// byte literals to command invocation
    ascii_keybinds: HashMap<BString, parse::Command<PostExpansion>>,

    debug_keystrokes: bool,
    loud: bool,

    /// n before end of history.len()
    /// 0 == not checking history
    history_visit: usize,
}

impl Session {
    pub fn new_noninteractive() -> Self {
        Self {
            raw: None,
            line: LineBuf::new(),
            history: Vec::new(),
            prev_path: b".".into(),
            builtins: HashMap::new(),
            vars: run::Vars::default(),
            funs: HashMap::new(),
            aliases: run::Aliases::new(),
            socket_running: None,
            path_cache: Default::default(),
            ctrlc: Default::default(),
            ti_keybinds: HashMap::new(),
            ascii_keybinds: HashMap::new(),
            debug_keystrokes: false,
            loud: false,
            history_visit: 0,
        }
    }
}

/// relative path -- in case it is a proper subpath the result starts with a slash `/`
fn relative_path(root: &Path, target: &Path) -> Option<String> {
    let root = root.to_string_lossy();
    let mut target = target.to_string_lossy().to_string();
    if !target.ends_with("/") {
        target += "/";
    }
    if let Some(("", leaf)) = target.split_once(&*root) {
        Some(leaf.into())
    } else {
        None
    }
}

fn pretty_cwd_res() -> io::Result<String> {
    let dir = std::env::current_dir()?;
    let mut s = if let Some(home_dir) = std::env::home_dir() {
        if let Some(rela) = relative_path(&home_dir, &dir) {
            format!("~{rela}")
        } else {
            dir.to_string_lossy().to_string()
        }
    } else {
        dir.to_string_lossy().to_string()
    };
    while s.ends_with("/") && s.len() > 1 {
        s.remove(s.len() - 1);
    }
    Ok(s)
}

fn pretty_cwd() -> BString {
    pretty_cwd_res()
        .unwrap_or_else(|_| String::new())
        .into_bytes()
}

impl Session {
    fn load_unevaled_prompt(&self) -> BString {
        match self.vars.lookup(&b"PROMPT"[..]) {
            Some(prompt) => prompt.into_owned(),
            None => {
                let mut prompt = BString::new();
                if cfg!(debug_assertions) {
                    prompt.push_all(b"dev ");
                }
                prompt.push_all(b"[$CWD_PRETTY]# ");
                prompt
            }
        }
    }

    fn prompt(this: Arc<Mutex<Self>>) -> BString {
        let mut prompt = this.lock().unwrap().load_unevaled_prompt();
        let mut x = Vec::with_capacity(prompt.len() + 2);
        x.push(b'"');
        x.append(&mut prompt);
        x.push(b'"');
        let parsed = match crate::parse::ExpString::parse_from_bytes(&x) {
            Ok(x) => x,
            Err(e) => {
                println!("{e:?}");
                return b"PARSE_ERROR$ ".to_vec();
            }
        };
        let mut expander = run::Executor::new(this);
        let Ok(expanded) = parsed.expand(&mut expander) else {
            return b"EXEC_ERROR$ ".to_vec();
        };
        expanded
    }

    fn clear_prompt(&mut self) {
        cursor::move_cursor(Direction::Right, self.line.distance_from_right_end());
        for _ in 0..self.line.len() {
            print!("\x08 \x08");
        }
        io::stdout().lock().flush().unwrap();
        self.line.clear();
    }

    fn prompt_clear(&mut self) {
        self.clear_prompt();
        self.history_visit = 0;
    }

    fn reprint_prompt(this: Arc<Mutex<Self>>) {
        io::stdout().write_all(&Self::prompt(this.clone())).unwrap();
        let this = this.lock().unwrap();
        this.line.display_pre();
        this.line.display_post(b"");
    }

    fn display_historic_entry(&mut self) {
        self.clear_prompt();
        let new = if self.history_visit == 0 {
            Vec::new()
        } else {
            self.history[self.history.len() - self.history_visit]
                .cmd
                .clone()
        };
        io::stdout().write_all(&new).unwrap();
        io::stdout().flush().unwrap();
        self.line.set_content(new);
    }

    fn history_up(&mut self) {
        if self.history_visit < self.history.len() {
            self.history_visit += 1;
            self.display_historic_entry();
        }
    }

    fn history_down(&mut self) {
        if self.history_visit > 0 {
            self.history_visit -= 1;
            self.display_historic_entry();
        }
    }

    fn type_bytes(&mut self, bs: &[u8]) {
        for b in bs.iter() {
            self.line.add(*b);
        }
        io::stdout().lock().write_all(&bs).unwrap();
        self.line.display_post(b"");
    }

    fn type_byte(&mut self, b: u8) {
        self.type_bytes(&[b]);
    }

    fn del_left(&mut self) {
        if self.line.del_left().is_some() {
            cursor::move_cursor(Direction::Left, 1);
            self.line.display_post(b" ");
        }
    }

    fn del_right(&mut self) {
        self.line.del_right();
        self.line.display_post(b" ");
    }

    fn del_left_or_previous(&mut self) {
        if self.line.is_empty() && !self.line.is_dirty() && !self.history.is_empty() {
            // take previous command for editing
            let cmd = self.history[self.history.len() - 1].cmd.clone();
            self.type_bytes(&cmd);
        } else {
            self.del_left();
        }
    }

    fn prompt_pipe_previous(&mut self) {
        if self.line.is_empty() && let Some(prev) = self.history.last() {
            let mut cmd = prev.cmd.clone();
            cmd.push_all(b" | ");
            self.type_bytes(&cmd);
        } else {
            self.type_byte(b'|');
        }
    }

    fn move_to_begin(&mut self) {
        cursor::move_cursor(Direction::Left, self.line.all_left());
        io::stdout().flush().unwrap();
    }

    fn move_to_end(&mut self) {
        cursor::move_cursor(Direction::Right, self.line.all_right());
        io::stdout().flush().unwrap();
    }

    fn del_left_word(&mut self) {
        let mut del = 0;
        while let Some(x) = self.line.get_left()
            && x == b' '
        {
            self.line.del_left();
            del += 1;
        }
        while let Some(x) = self.line.get_left()
            && x != b' '
        {
            self.line.del_left();
            del += 1;
        }
        cursor::move_cursor(Direction::Left, del);
        self.line.display_post(&vec![b' '; del]);
    }

    fn del_right_word(&mut self) {
        let mut del = 0;
        while let Some(x) = self.line.get_right()
            && x == b' '
        {
            self.line.del_right();
            del += 1;
        }
        while let Some(x) = self.line.get_right()
            && x != b' '
        {
            self.line.del_right();
            del += 1;
        }
        self.line.display_post(&vec![b' '; del]);
    }

    fn cursor_left(&mut self) {
        if self.line.left() {
            move_cursor(Direction::Left, 1);
            io::stdout().lock().flush().unwrap();
        }
    }

    fn cursor_right(&mut self) {
        if self.line.right() {
            move_cursor(Direction::Right, 1);
            io::stdout().lock().flush().unwrap();
        }
    }

    // move to next
    fn cursor_left_word(&mut self) {
        let mut i = 0;

        // find word
        while let Some(b' ') = self.line.get_left() {
            self.line.left();
            i += 1;
        }

        // skip it
        while let Some(x) = self.line.get_left()
            && !x.is_ascii_whitespace()
        {
            self.line.left();
            i += 1;
        }

        cursor::move_cursor(Direction::Left, i);
        io::stdout().flush().unwrap();
    }

    fn cursor_right_word(&mut self) {
        let mut i = 0;

        // find word
        while let Some(b' ') = self.line.get_right() {
            self.line.right();
            i += 1;
        }

        // skip it
        while let Some(x) = self.line.get_right()
            && !x.is_ascii_whitespace()
        {
            self.line.right();
            i += 1;
        }

        cursor::move_cursor(Direction::Right, i);
        io::stdout().flush().unwrap();
    }

    fn complete(session: Arc<Mutex<Session>>) {
        let cmd = session.lock().unwrap().line.pre().to_vec();

        let comp = completion(session.clone(), &cmd);

        let mut se = session.lock().unwrap();

        se.type_bytes(&comp.shared_prefix);

        if comp.suggestions.len() > 1 {
            print!("\r\n");
            for s in comp.suggestions {
                io::stdout().lock().write_all(&s.display).unwrap();
                println!();
            }
            drop(se);
            Self::reprint_prompt(session);
        }
    }

    fn try_submit_command(session: Arc<Mutex<Session>>) {
        let mut se = session.lock().unwrap();
        let line = se.line.into_bytes();

        if !line.is_empty() {
            let parsed = match parse::do_parse(&line) {
                Ok(p) => p,
                Err(_) => {
                    se.line.add(b'\n');
                    print!("\r\n> ");
                    return;
                }
            };
            print!("\r\n");
            let entry = HistoryEntry::new(line.clone());
            history::persist(&entry);
            se.history.push(entry);
            se.history_visit = 0;
            se.line.dump();
            drop(se);
            run::run(session.clone(), parsed);
        }
    }

    fn screen_clear(this: Arc<Mutex<Self>>) {
        clear_screen();
        Self::reprint_prompt(this);
    }

    fn raw_enable(&self) {
        if let Some(r) = &self.raw {
            r.enable();
        }
    }

    fn raw_disable(&self) {
        if let Some(r) = &self.raw {
            r.disable();
        }
    }
}

fn exec_rc_file(se: Arc<Mutex<Session>>) {
    let _ = run::source(
        se,
        basedir::config_dir().join(".pishrc").as_os_str().as_bytes(),
    );
}

pub fn event_loop() {
    fs::create_dir_all(basedir::config_dir()).unwrap();
    fs::create_dir_all(basedir::data_dir()).unwrap();
    fs::create_dir_all(basedir::state_dir()).unwrap();

    history::setup();
    ansi::setup();

    let stdin = io::stdin();

    let fd = stdin.as_raw_fd();
    let raw = ScopedRawMode::on_fd(fd);
    raw.enable();

    let se = Session {
        raw: Some(raw),
        line: LineBuf::new(),
        history: Vec::new(),
        builtins: run::builtin_map(),
        prev_path: vec![b'.'],
        history_visit: 0,
        socket_running: None,
        vars: run::Vars::default(),
        funs: HashMap::new(),
        aliases: run::Aliases::new(),
        path_cache: Default::default(),
        ctrlc: Default::default(),
        debug_keystrokes: false,
        loud: false,
        ti_keybinds: HashMap::new(),
        ascii_keybinds: HashMap::new(),
    };

    let session = Arc::new(Mutex::new(se));
    exec_rc_file(session.clone());

    session.lock().unwrap().loud = true;
    Session::reprint_prompt(session.clone());

    completion::populate_path_cache(session.clone());

    let _sock_dropper = export_fun::listen(session.clone());
    let _ctrlc = ctrlc::setup(session.clone());

    'repl: loop {
        let mut se = session.lock().unwrap();

        let Some(key) = ansi::read(se.debug_keystrokes) else {
            break;
        };

        if se.debug_keystrokes {
            println!("{key:?}");
        }

        if let Some(cmd) = se.ascii_keybinds.get(key.as_bytes()) {
            let cmd = cmd.clone();
            drop(se);
            // not sure if/how to report this error - would be strange to print something to console every time a keybind command returns nonzero exit code.
            let _ = run::run_quiet(session.clone(), cmd);
            continue 'repl;
        }

        match key {
            ansi::KbInput::Key([x]) => se.type_byte(x),
            ansi::KbInput::Escape(escape) => {
                for terminfo_key in escape.keys.iter() {
                    if let Some(cmd) = se.ti_keybinds.get(terminfo_key.as_bytes()) {
                        let cmd = cmd.clone();
                        drop(se);
                        // not sure if/how to report this error - would be strange to print something to console every time a keybind command returns nonzero exit code.
                        let _ = run::run_quiet(session.clone(), cmd);
                        continue 'repl;
                    }
                }
            }
            ansi::KbInput::InvalidEscape(_) => continue,
        }
    }

    session.lock().unwrap().raw_disable();
}

pub fn icon() -> BString {
    const DATA: &[u8] = include_bytes!("icon.txt");
    const COLOR0: &[u8] = b"\x1b[100m";
    const COLOR1: &[u8] = b"\x1b[47m";
    const COLOR_RESET: &[u8] = b"\x1b[0m";
    let mut color = COLOR0;
    let mut buf = BString::new();

    for line in DATA.split(|x| *x == b'\n') {
        if line.starts_with(b"-") {
            color = COLOR1;
            continue;
        }

        let mut colored = false;
        for &b in line {
            if b == b'#' {
                if !colored {
                    buf.push_all(color);
                    colored = true;
                }
            } else if colored {
                buf.push_all(COLOR_RESET);
                colored = false;
            }
            buf.push_all(b"  ");
        }
        if colored {
            buf.push_all(COLOR_RESET);
        }
        buf.push_all(b"\r\n");
    }

    buf
}