aboutsummaryrefslogtreecommitdiffstats
path: root/src/ansi/mod.rs
blob: 0b43edee13929b80bf141775cb1fb3883183c2ef (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
use std::{collections::BTreeMap, io::Read, os::unix::ffi::OsStrExt, sync::RwLock};

use crate::cursor::Direction;

pub enum KeyboardInput {
    Eof,
    Key(u8),
    CtrlA,
    CtrlB,
    CtrlC,
    CtrlE,
    CtrlD,
    CtrlL,
    CtrlR,
    Arrow(Direction),
    CtrlArrow(Direction),
    DeleteLeft,
    DeleteRight,
    CtrlDeleteRight,
    Home,
    End,
}

fn read1() -> Option<u8> {
    let mut buf = [0];
    match std::io::stdin().lock().read_exact(&mut buf) {
        Ok(_) => Some(buf[0]),
        Err(_) => None,
    }
}

fn byte_to_dir(b: u8) -> Option<Direction> {
    use Direction::*;
    match b {
        b'A' => Some(Up),
        b'B' => Some(Down),
        b'C' => Some(Right),
        b'D' => Some(Left),
        _ => None,
    }
}

fn read_escape(debug: bool) -> KeyboardInput {
    use Direction::*;
    use KeyboardInput::*;

    let mut seq = vec![match read1() {
        Some(x) => x,
        None => return Eof,
    }];

    if seq[0] == b'[' {
        // still more
        while {
            let last = seq[seq.len() - 1];
            !(0x40..=0x7E).contains(&last) || seq.len() == 1
        } {
            seq.push(match read1() {
                Some(x) => x,
                None => return Eof,
            });
        }

        if debug {
            println!("escape: {}", seq.escape_ascii());
        }

        match seq[1] {
            b'3' => {
                if seq.len() > 2 && seq[2] == b'~' {
                    DeleteRight
                } else {
                    todo!("unhandled: {}", seq.escape_ascii());
                }
            }
            b'H' => Home,
            b'F' => End,
            b'd' => CtrlDeleteRight,

            // Ctrl Arrow
            b'1' => {
                if seq[1..].starts_with(b"1;5") {
                    if seq.len() == 4 {
                        todo!("idk what this is.");
                    }
                    match seq[4] {
                        b'A' => CtrlArrow(Up),
                        b'B' => CtrlArrow(Down),
                        b'C' => CtrlArrow(Right),
                        b'D' => CtrlArrow(Left),
                        _ => todo!("unhandled {}", seq.escape_ascii()),
                    }
                } else {
                    todo!("unhandled {}", seq[1..].escape_ascii())
                }
            }

            x => {
                if let Some(dir) = byte_to_dir(x) {
                    Arrow(dir)
                } else {
                    todo!("escape characters {}", seq[1..].escape_ascii())
                }
            }
        }
    } else {
        if debug {
            println!("escape: {}", seq.escape_ascii());
        }
        match seq[0] {
            b'd' => CtrlDeleteRight,
            x => todo!("unhandled escape code: ESC {x}"),
        }
    }
}

pub fn read(debug: bool) -> Option<KbInput<'static>> {
    let trie = EscapeTrie::from(ti());
    let trie = Box::leak(Box::new(trie)); // TODO don't leak memory, this is only temporary
    let mut reader = EscapingStdinReader::new(trie);
    loop {
        let Some(b) = read1() else {
            break None;
        };
        match reader.process_byte(b) {
            ByteProcessingResult::Done(kb) => {
                if debug {
                    if let KbInput::Escape(e) = &kb {
                        for k in e.keys.iter() {
                            print!("{k} ")
                        }
                    }
                    println!("{}\r", kb.as_bytes().escape_ascii());
                }
                if let KbInput::InvalidEscape(x) = &kb {
                    if x.len() == 1 {
                        break Some(KbInput::Key([x[0]]));
                    }
                }
                break Some(kb);
            }
            ByteProcessingResult::Continue(r) => reader = r,
        }
    }
}

struct EscapingStdinReader<'a> {
    buf: Vec<u8>,
    trie: &'a EscapeTrie,
}

enum ByteProcessingResult<'a> {
    Done(KbInput<'a>),
    Continue(EscapingStdinReader<'a>),
}

impl<'a> EscapingStdinReader<'a> {
    pub fn new(trie: &'a EscapeTrie) -> Self {
        Self {
            buf: Vec::new(),
            trie,
        }
    }

    pub fn process_byte(mut self, byte: u8) -> ByteProcessingResult<'a> {
        match self.trie {
            EscapeTrie::Done(_) => ByteProcessingResult::Done(KbInput::Key([byte])),
            EscapeTrie::More(trie) => {
                self.buf.push(byte);
                match trie.get(&byte) {
                    Some(EscapeTrie::Done(keys)) => {
                        ByteProcessingResult::Done(KbInput::Escape(Escape {
                            keys: &keys[..],
                            value: self.buf,
                        }))
                    }
                    Some(trie) => {
                        self.trie = trie;
                        ByteProcessingResult::Continue(self)
                    }
                    None => ByteProcessingResult::Done(KbInput::InvalidEscape(self.buf)),
                }
            }
        }
    }
}

enum EscapeTrie {
    Done(Vec<&'static str>),
    More(BTreeMap<u8, EscapeTrie>),
}

#[derive(Debug)]
pub enum KbInput<'a> {
    Key([u8; 1]),
    Escape(Escape<'a>),
    InvalidEscape(Vec<u8>),
}

impl<'a> KbInput<'a> {
    pub fn as_bytes(&'a self) -> &'a [u8] {
        match self {
            KbInput::Key(x) => &x[..],
            KbInput::Escape(e) => &e.value[..],
            KbInput::InvalidEscape(e) => &e[..],
        }
    }
}

#[derive(Debug)]
pub struct Escape<'a> {
    pub keys: &'a [&'a str],
    pub value: Vec<u8>,
}

use terminfo_lean::parse::Terminfo;

static TERMINFO: RwLock<Option<&'static Terminfo<'static>>> = RwLock::new(None);

fn parse_terminfo() -> Result<Terminfo<'static>, ()> {
    let term = std::env::var_os("TERM").unwrap_or_else(|| "xterm".into());
    let terminfo_file_path = terminfo_lean::locate::locate(&term)
        .map_err(|e| println!("failed to locate terminfo file for terminal {term:?}: {e:?}",))?;
    let mut terminfo_file = std::fs::File::open(&terminfo_file_path).map_err(|e| {
        println!("failed to open terminfo file at location {terminfo_file_path:?}: {e:?}")
    })?;
    let mut buf = Vec::new();
    terminfo_file.read_to_end(&mut buf).map_err(|e| {
        println!("failed to read terminfo file at location {terminfo_file_path:?}: {e:?}")
    })?;
    buf.shrink_to_fit();
    let terminfo = terminfo_lean::parse::parse(buf.leak()).map_err(|e| {
        println!("failed to parse terminfo file at location {terminfo_file_path:?}: {e:?}")
    })?;
    Ok(terminfo)
}

fn parse_terminfo_backup() -> Terminfo<'static> {
    todo!("panic-safe backup terminfo")
}

pub fn setup() {
    let ti = parse_terminfo().unwrap_or_else(|_| {
        println!("using backup terminfo (might not be correct for this terminal)");
        parse_terminfo_backup()
    });
    let ti = Box::leak(Box::new(ti));
    TERMINFO.clear_poison();
    *TERMINFO.write().unwrap() = Some(ti);
}

pub fn ti() -> &'static Terminfo<'static> {
    TERMINFO.read().unwrap().unwrap()
}

fn is_parametrized(x: &[u8]) -> bool {
    let mut pct = false;
    for &b in x {
        if b == b'%' {
            pct = !pct;
        } else if pct {
            return true;
        }
    }
    false
}

fn trie_from_words(words: Vec<(&'static str, &[u8])>) -> EscapeTrie {
    let mut tree = BTreeMap::new();
    let mut all_empty = true;

    for (key, val) in words.iter() {
        if let Some(byte) = val.get(0) {
            all_empty = false;
            tree.entry(byte)
                .or_insert_with(Vec::new)
                .push((*key, &val[1..]));
        }
    }

    if all_empty {
        EscapeTrie::Done(words.into_iter().map(|x| x.0).collect())
    } else {
        let trie = tree
            .into_iter()
            .map(|(k, v)| (*k, trie_from_words(v)))
            .collect();
        EscapeTrie::More(trie)
    }
}

impl From<&Terminfo<'static>> for EscapeTrie {
    fn from(ti: &Terminfo<'static>) -> Self {
        let w: Vec<(&'static str, &'static [u8])> = ti
            .strings
            .iter()
            .filter(|(k, v)| k.starts_with("k") && !is_parametrized(v))
            .map(|(k, v)| (*k, *v))
            .collect();
        trie_from_words(w)
    }
}