summaryrefslogtreecommitdiffstats
path: root/rsnix/src/tty.rs
blob: ad33cb3c5b15c9c8d28282a29da2b8c61e221f7c (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
//! Line discipline over the keyboard — the kernel's tty layer.
//!
//! Keys come from either the PS/2 controller (IRQ-fed scancode ring) or the
//! USB HID boot keyboard (polled UHCI driver).  Both are translated to the
//! same `KeyEvent` space, so the shell is input-source agnostic.
//!
//! Two modes, like a real UNIX terminal:
//! - **canonical** (`read_line`): input is echoed, buffered until Enter,
//!   ^C cancels the line, ^D on an empty line is EOF.
//! - **raw** (`read_byte` / `try_read_byte`): keys are translated to the
//!   classic terminal byte protocol (arrows → `ESC [ A–D`, Backspace →
//!   `0x7f`, ^X → `0x18`, …) and delivered one byte at a time, with no echo.
//!   Multi-byte sequences are queued internally so `read_byte` returns them
//!   in order.
//!
//! `interrupt_pressed` is the cooperative-interrupt check used by streaming
//! commands (cat/hexdump): it drains the keyboard non-blockingly and reports
//! whether ^C was seen.

use crate::ps2::{self, KeyEvent};
use crate::strbuf;
use crate::{gop, serial};

/// Max characters a single typed line can hold.  Long enough that no
/// realistic command line gets silently cut — the terminal wraps the
/// echo at the screen edge, and the full line is what's submitted.
pub const LINE_BUF_SIZE: usize = 1024;

/// Result of one canonical line-input session.
#[allow(clippy::large_enum_variant)] // stack buffer by design (no heap churn)
pub enum LineInput {
    Line(strbuf::String<LINE_BUF_SIZE>),
    Interrupted, // ^C
    Eof,         // ^D on an empty line
}

// Raw-mode byte queue: holds the tail of a multi-byte key sequence.
static mut RAW_QUEUE: [u8; 8] = [0; 8];
static mut RAW_LEN: usize = 0;

/// Combined blocking key poll: USB HID keyboard first (polled UHCI), then
/// the PS/2 path (which parks via `hlt` until an IRQ-fed scancode lands).
fn poll_key() -> KeyEvent {
    loop {
        // A GUI window has focus: the keyboard pump owns the keys.  Park so
        // the shell/editor don't steal input from the focused app.
        if crate::wm::focused().is_some() {
            crate::sched::sleep_ms(5);
            continue;
        }
        if let Some(ev) = crate::uhci::try_poll_key() {
            return ev;
        }
        if let Some(ev) = ps2::try_poll_key() {
            return ev;
        }
        // No key ready: park briefly, then re-check focus (so a focus change
        // to a GUI window is noticed instead of blocking on a stolen key).
        crate::sched::sleep_ms(5);
    }
}

/// Combined non-blocking key poll (USB first, then PS/2).  Returns `None`
/// while a GUI window is focused (the keyboard pump owns the keys).
fn try_poll_key() -> Option<KeyEvent> {
    if crate::wm::focused().is_some() {
        return None;
    }
    crate::uhci::try_poll_key().or_else(ps2::try_poll_key)
}

// ---------------------------------------------------------------------------
// canonical mode
// ---------------------------------------------------------------------------

/// Read one line in canonical mode: echo every key, ^C cancels the line,
/// ^D on an empty line is EOF.  Echo goes to the terminal (GOP) and serial.
pub fn read_line() -> LineInput {
    // Interactive input: make sure deferred scrolls are pushed first so
    // the screen shows the current state (no-op when nothing is pending).
    crate::vt::sync_scroll();
    let mut buf = strbuf::String::<LINE_BUF_SIZE>::new();
    loop {
        match poll_key() {
            KeyEvent::Enter => {
                gop::put_char('\n');
                serial::write_str("\r\n");
                return LineInput::Line(buf);
            }
            KeyEvent::Ctrl('c') => {
                // Cancel the current line — like a real terminal, echo ^C.
                buf.clear();
                gop::put_char('^');
                gop::put_char('C');
                gop::put_char('\n');
                serial::write_str("^C\r\n");
                return LineInput::Interrupted;
            }
            KeyEvent::Ctrl('d') => {
                if buf.is_empty() {
                    // EOF on an empty line — the caller decides what to do.
                    gop::put_char('^');
                    gop::put_char('D');
                    gop::put_char('\n');
                    serial::write_str("^D\r\n");
                    return LineInput::Eof;
                }
                // ^D with text on the line: ignored (bash semantics).
            }
            KeyEvent::Char(c) if c.is_ascii_graphic() || c == ' ' => {
                if buf.push(c).is_ok() {
                    gop::put_char(c);
                    let mut s = [0u8; 4];
                    let s = c.encode_utf8(&mut s);
                    serial::write_str(s);
                }
            }
            KeyEvent::Backspace => {
                if buf.pop().is_some() {
                    gop::put_char('\x08');
                    // Serial backspace: BS SP BS (standard terminal protocol)
                    serial::write_str("\x08 \x08");
                }
            }
            KeyEvent::Tab => {
                for _ in 0..4 {
                    if buf.push(' ').is_ok() {
                        gop::put_char(' ');
                        serial::write_str(" ");
                    }
                }
            }
            _ => {}
        }
    }
}

/// Read one line in canonical mode from the task's message queue (for
/// windowed shells).  Same semantics as `read_line` but keys arrive as
/// `TaskMsg::Key` instead of from the global PS/2 queue.  Returns `None`
/// on `TaskMsg::Close` (window was closed).
/// Read one line in canonical mode from the task's message queue (for
/// windowed shells).  Same semantics as `read_line` but keys arrive as
/// `TaskMsg::Key` instead of from the global PS/2 queue.  Returns `None`
/// on `TaskMsg::Close` (window was closed).
///
/// Handles `TaskMsg::Focus` to toggle the global `ACTIVE` redirect so
/// gop_print! goes to the right terminal buffer.
pub fn read_line_from_queue(term: &mut crate::vt::Terminal) -> Option<LineInput> {
    crate::vt::sync_scroll();
    let mut buf = strbuf::String::<LINE_BUF_SIZE>::new();
    loop {
        match crate::sched::recv_blocking() {
            crate::sched::TaskMsg::Key(ev) => match ev {
                KeyEvent::Enter => {
                    gop::put_char('\n');
                    serial::write_str("\r\n");
                    return Some(LineInput::Line(buf));
                }
                KeyEvent::Ctrl('c') => {
                    buf.clear();
                    gop::put_char('^');
                    gop::put_char('C');
                    gop::put_char('\n');
                    serial::write_str("^C\r\n");
                    return Some(LineInput::Interrupted);
                }
                KeyEvent::Ctrl('d') => {
                    if buf.is_empty() {
                        gop::put_char('^');
                        gop::put_char('D');
                        gop::put_char('\n');
                        serial::write_str("^D\r\n");
                        return Some(LineInput::Eof);
                    }
                }
                KeyEvent::Char(c) if c.is_ascii_graphic() || c == ' ' => {
                    if buf.push(c).is_ok() {
                        gop::put_char(c);
                        let mut s = [0u8; 4];
                        let s = c.encode_utf8(&mut s);
                        serial::write_str(s);
                    }
                }
                KeyEvent::Backspace => {
                    if buf.pop().is_some() {
                        gop::put_char('\x08');
                        serial::write_str("\x08 \x08");
                    }
                }
                KeyEvent::Tab => {
                    for _ in 0..4 {
                        if buf.push(' ').is_ok() {
                            gop::put_char(' ');
                            serial::write_str(" ");
                        }
                    }
                }
                _ => {}
            },
            crate::sched::TaskMsg::Focus(gained) => {
                if gained {
                    crate::vt::set_active(term as *mut crate::vt::Terminal);
                    // Re-composite the full window so content is visible
                    // immediately (focus() only redraws the title bar).
                    term.flush();
                } else {
                    crate::vt::set_active(core::ptr::null_mut());
                }
            }
            crate::sched::TaskMsg::Close => return None,
            _ => {}
        }
    }
}

/// Non-blocking drain of the keyboard: true if a ^C is pending.  Used by
/// streaming commands (cat/hexdump) so a long dump can be interrupted.
pub fn interrupt_pressed() -> bool {
    let mut pressed = false;
    while let Some(ev) = try_poll_key() {
        if matches!(ev, KeyEvent::Ctrl('c')) {
            pressed = true;
        }
    }
    pressed
}

// ---------------------------------------------------------------------------
// raw mode
// ---------------------------------------------------------------------------

/// Blocking read of the next raw-mode byte.  Keys arrive translated to the
/// terminal byte protocol; multi-byte sequences are delivered in order.
pub fn read_byte() -> u8 {
    // Interactive (raw) input: push deferred scrolls so the full-screen
    // app draws over a current framebuffer.
    crate::vt::sync_scroll();
    loop {
        if let Some(b) = pop_raw() {
            return b;
        }
        let ev = poll_key();
        enqueue_key(ev);
    }
}

/// Non-blocking raw read: Some(byte) if one is available, else None.
pub fn try_read_byte() -> Option<u8> {
    if let Some(b) = pop_raw() {
        return Some(b);
    }
    match try_poll_key() {
        Some(ev) => {
            enqueue_key(ev);
            pop_raw()
        }
        None => None,
    }
}

fn pop_raw() -> Option<u8> {
    unsafe {
        if RAW_LEN == 0 {
            return None;
        }
        let b = RAW_QUEUE[0];
        for i in 1..RAW_LEN {
            RAW_QUEUE[i - 1] = RAW_QUEUE[i];
        }
        RAW_LEN -= 1;
        Some(b)
    }
}

fn enqueue_key(ev: KeyEvent) {
    let mut q = [0u8; 8];
    let n: usize = match ev {
        KeyEvent::Char(c) if c.is_ascii() => {
            q[0] = c as u8;
            1
        }
        KeyEvent::Enter => {
            q[0] = 0x0d;
            1
        }
        KeyEvent::Backspace => {
            q[0] = 0x7f;
            1
        }
        KeyEvent::Tab => {
            q[0] = 0x09;
            1
        }
        KeyEvent::Escape => {
            q[0] = 0x1b;
            1
        }
        KeyEvent::Ctrl(c) => {
            q[0] = (c as u8) & 0x1f;
            1
        }
        KeyEvent::ArrowUp => {
            q[..3].copy_from_slice(b"\x1b[A");
            3
        }
        KeyEvent::ArrowDown => {
            q[..3].copy_from_slice(b"\x1b[B");
            3
        }
        KeyEvent::ArrowRight => {
            q[..3].copy_from_slice(b"\x1b[C");
            3
        }
        KeyEvent::ArrowLeft => {
            q[..3].copy_from_slice(b"\x1b[D");
            3
        }
        KeyEvent::CtrlArrow(0) => {
            q[..6].copy_from_slice(b"\x1b[1;5A");
            6
        }
        KeyEvent::CtrlArrow(1) => {
            q[..6].copy_from_slice(b"\x1b[1;5B");
            6
        }
        KeyEvent::CtrlArrow(2) => {
            q[..6].copy_from_slice(b"\x1b[1;5D");
            6
        }
        KeyEvent::CtrlArrow(3) => {
            q[..6].copy_from_slice(b"\x1b[1;5C");
            6
        }
        KeyEvent::Home => {
            q[..3].copy_from_slice(b"\x1b[H");
            3
        }
        KeyEvent::End => {
            q[..3].copy_from_slice(b"\x1b[F");
            3
        }
        KeyEvent::PageUp => {
            q[..4].copy_from_slice(b"\x1b[5~");
            4
        }
        KeyEvent::PageDown => {
            q[..4].copy_from_slice(b"\x1b[6~");
            4
        }
        KeyEvent::Delete => {
            q[..4].copy_from_slice(b"\x1b[3~");
            4
        }
        _ => return,
    };
    unsafe {
        for (i, b) in q.iter().take(n).enumerate() {
            RAW_QUEUE[i] = *b;
        }
        RAW_LEN = n;
    }
}