vce 0.1.1

A stateful virtual OS engine with an embeddable machine and shell API
Documentation
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! The host terminal adapter.
//!
//! The host terminal adapter: renders the pure-state [`TerminalModel`] onto
//! a real host terminal and translates host key events into virtual
//! [`KeyEvent`]s.
//!
//! The virtual terminal is never implemented by clearing and reprinting: the
//! model holds the screen state, and the host adapter only repaints the
//! frame when the model's [`TerminalModel::version`] changes — the same
//! approach real terminal emulators take internally.

use std::io::{Stdout, Write};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use crate::SessionControl;
use crossterm::event::{Event, KeyCode, KeyEvent as CrosstermKeyEvent, KeyEventKind, KeyModifiers};
use engine::io::{InputMode, Key, KeyEvent, Size, Terminal};
use terminal::{Color, Style, TerminalModel};

/// A [`Terminal`] implementation backed by a shared virtual terminal model.
///
/// The model is shared between the shell, the host key reader, and the
/// renderer through an internal mutex; the `&mut self` trait methods just
/// synchronize on it. This lets a background thread pump host keys into the
/// model's queue while a command polls [`Terminal::next_key`].
pub struct HostTerminal {
    model: Arc<Mutex<TerminalModel>>,
    control: SessionControl,
}

impl HostTerminal {
    /// Creates a host terminal over a fresh model at the given size.
    pub fn new(size: Size, control: SessionControl) -> Self {
        Self {
            model: Arc::new(Mutex::new(TerminalModel::new(size))),
            control,
        }
    }

    /// The shared model handle (for the renderer and key pump).
    pub fn model(&self) -> &Arc<Mutex<TerminalModel>> {
        &self.model
    }
}

impl Terminal for HostTerminal {
    fn size(&self) -> Size {
        self.model.lock().expect("model lock poisoned").size()
    }

    fn next_key(&mut self) -> Option<KeyEvent> {
        loop {
            if self.control.interruption().is_some() {
                return Some(KeyEvent::ctrl('c'));
            }
            if let Some(key) = self.model.lock().expect("model lock poisoned").next_key() {
                return Some(key);
            }
            thread::sleep(KEY_POLL);
        }
    }

    fn push_keys(&mut self, keys: &[KeyEvent]) {
        self.model
            .lock()
            .expect("model lock poisoned")
            .push_keys(keys);
    }

    fn write(&mut self, bytes: &[u8]) {
        self.model.lock().expect("model lock poisoned").write(bytes);
    }

    fn enter_alternate_screen(&mut self) {
        self.model
            .lock()
            .expect("model lock poisoned")
            .enter_alternate_screen();
    }

    fn leave_alternate_screen(&mut self) {
        self.model
            .lock()
            .expect("model lock poisoned")
            .leave_alternate_screen();
    }

    fn input_mode(&self) -> InputMode {
        self.model.lock().expect("model lock poisoned").input_mode()
    }

    fn set_input_mode(&mut self, mode: InputMode) {
        self.model
            .lock()
            .expect("model lock poisoned")
            .set_input_mode(mode);
    }

    fn flush(&mut self) {}
}

/// An [`engine::Output`] that writes into the virtual terminal model.
///
/// Commands that are not interactive (for example `ls`) write their stdout
/// here, so their output lands in the terminal's screen state just like a
/// real terminal.
#[derive(Clone)]
pub struct TerminalOutput {
    model: Arc<Mutex<TerminalModel>>,
}

impl TerminalOutput {
    /// Creates an output over the same model as a [`HostTerminal`].
    pub fn new(terminal: &HostTerminal) -> Self {
        Self {
            model: Arc::clone(terminal.model()),
        }
    }
}

impl engine::Output for TerminalOutput {
    fn write(&mut self, bytes: &[u8]) -> Result<(), engine::OutputError> {
        self.model.lock().expect("model lock poisoned").write(bytes);
        Ok(())
    }
}

/// An [`engine::Input`] that reads keys from the virtual terminal.
///
/// Commands that read standard input (`cat`, `sh`, `read`) receive the
/// user's typed keys translated to the byte stream a real terminal would
/// deliver: characters as UTF-8, Enter as a newline, Backspace as DEL,
/// Ctrl+C as ETX, and Ctrl+D as end of stream. Reading blocks until a key
/// arrives, like a real terminal wait.
pub struct TerminalInput {
    model: Arc<Mutex<TerminalModel>>,
    /// Encoded bytes not yet delivered because the caller's buffer was
    /// smaller than the key sequence that produced them.
    pending: Vec<u8>,
    control: SessionControl,
}

impl TerminalInput {
    /// Creates an input over the same model as a [`HostTerminal`].
    pub fn new(terminal: &HostTerminal) -> Self {
        Self {
            model: Arc::clone(terminal.model()),
            pending: Vec::new(),
            control: terminal.control.clone(),
        }
    }
}

impl engine::Input for TerminalInput {
    fn read(&mut self, buffer: &mut [u8]) -> Result<usize, engine::InputError> {
        if buffer.is_empty() {
            return Ok(0);
        }
        if self.control.interruption().is_some() {
            return Ok(0);
        }
        // Deliver any carried-over bytes before reading fresh keys, so no
        // part of a key sequence is ever dropped.
        if !self.pending.is_empty() {
            let count = buffer.len().min(self.pending.len());
            buffer[..count].copy_from_slice(&self.pending[..count]);
            self.pending.drain(..count);
            return Ok(count);
        }
        let mut bytes: Vec<u8> = Vec::new();
        while bytes.is_empty() {
            let key = {
                let mut model = self.model.lock().expect("model lock poisoned");
                model.next_key()
            };
            let Some(key) = key else {
                thread::sleep(KEY_POLL);
                continue;
            };
            match key.key {
                Key::Character if !key.ctrl && !key.alt => {
                    if let Some(character) = key.character {
                        let mut encoded = [0u8; 4];
                        bytes.extend_from_slice(character.encode_utf8(&mut encoded).as_bytes());
                    }
                }
                Key::Enter => bytes.push(b'\n'),
                Key::Backspace => bytes.push(0x7f),
                Key::Tab => bytes.push(b'\t'),
                Key::Escape => bytes.push(0x1b),
                Key::Character if key.ctrl && key.character == Some('d') => return Ok(0),
                Key::Character if key.ctrl && key.character == Some('c') => {
                    bytes.push(0x03);
                }
                _ => {}
            }
        }
        let count = bytes.len().min(buffer.len());
        buffer[..count].copy_from_slice(&bytes[..count]);
        // A sequence longer than the caller's buffer carries over; it is
        // delivered by the next read.
        self.pending.extend_from_slice(&bytes[count..]);
        Ok(count)
    }
}

/// Repaints the host terminal when the model changed.
///
/// Renders the visible screen buffer as a frame: home the cursor, draw each
/// row (padding to the full width), then place the cursor. Styles are
/// ignored for now; a later pass can render colors.
pub fn render(
    host: &mut Stdout,
    model: &TerminalModel,
    last_version: &mut u64,
) -> std::io::Result<()> {
    if model.version() == *last_version {
        return Ok(());
    }
    *last_version = model.version();

    let size = model.size();
    let screen = model.visible_screen();
    let first_frame = *last_version == 0;
    let mut frame = String::new();
    // Reset any attributes the host terminal may carry (for example from
    // `cargo`'s colored output) so text is always drawn in the default
    // style, and home the cursor.
    frame.push_str("\x1b[0m\x1b[H");
    // The first frame also clears the visible screen, so stale content from
    // before the app started (the previous shell prompt, build output)
    // cannot linger or confuse the view.
    if first_frame {
        frame.push_str("\x1b[2J");
    }
    for (index, row) in screen.rows().enumerate() {
        // Every row is positioned absolutely and erased before drawing; no
        // cursor-motion state is relied upon, so the frame renders
        // identically on any VT-compatible terminal. Styled runs (reverse
        // video, bold, underline, colors) are emitted as SGR sequences so
        // applications such as `nano` and `man` render their chrome like the
        // real thing.
        frame.push_str(&format!("\x1b[{};1H", index + 1));
        frame.push_str("\x1b[K");
        let width = usize::from(size.cols);
        let mut styled = String::new();
        let mut current = Style::plain();
        for cell in row {
            if cell.style != current {
                push_style_reset(&mut styled, &current);
                current = cell.style;
                push_style(&mut styled, &current);
            }
            styled.push(cell.ch);
        }
        push_style_reset(&mut styled, &current);
        let cell_count = styled.chars().count();
        if cell_count < width {
            styled.push_str(&" ".repeat(width - cell_count));
        }
        frame.push_str(&styled);
    }
    let (row, col) = screen.cursor();
    frame.push_str(&format!("\x1b[{};{}H", row + 1, col + 1));
    if model.cursor_visible() {
        frame.push_str("\x1b[?25h");
    } else {
        frame.push_str("\x1b[?25l");
    }
    host.write_all(frame.as_bytes())?;
    host.flush()
}

/// Emits the SGR reset, unless the style is already plain.
fn push_style_reset(out: &mut String, style: &Style) {
    if *style != Style::plain() {
        out.push_str("\x1b[0m");
    }
}

/// Emits the SGR sequence enabling a cell style.
fn push_style(out: &mut String, style: &Style) {
    let mut params: Vec<String> = Vec::new();
    if style.bold {
        params.push("1".to_owned());
    }
    if style.underline {
        params.push("4".to_owned());
    }
    if style.reverse {
        params.push("7".to_owned());
    }
    match style.fg {
        Color::Default => {}
        Color::Standard(n) if n < 8 => params.push(format!("{}", 30 + n)),
        Color::Standard(n) => params.push(format!("{}", 90 + n - 8)),
        Color::Rgb(r, g, b) => params.push(format!("38;2;{r};{g};{b}")),
    }
    match style.bg {
        Color::Default => {}
        Color::Standard(n) if n < 8 => params.push(format!("{}", 40 + n)),
        Color::Standard(n) => params.push(format!("{}", 100 + n - 8)),
        Color::Rgb(r, g, b) => params.push(format!("48;2;{r};{g};{b}")),
    }
    if params.is_empty() {
        return;
    }
    out.push_str("\x1b[");
    out.push_str(&params.join(";"));
    out.push('m');
}

/// The polling interval of the render watcher.
const RENDER_POLL: Duration = Duration::from_millis(16);

/// The interval between host-size re-checks.
const SIZE_CHECK_POLL: Duration = Duration::from_millis(250);

/// How long a key consumer sleeps while the model's key queue is empty.
const KEY_POLL: Duration = Duration::from_millis(4);

/// Spawns a render watcher that repaints the host screen while a command is
/// running.
///
/// Commands mutate the shared model during execution (for example `man`
/// enters the alternate screen and renders into it), but the main thread is
/// blocked inside the command and cannot repaint. The watcher polls the
/// model's version and redraws when it changes, so interactive screens are
/// visible live. While the shell is idle at the prompt, the main thread
/// renders and the watcher does nothing.
///
/// The watcher also re-checks the host terminal's actual size and resizes
/// the model when they diverge. A stale startup size (or a window resized
/// after launch) otherwise makes frames overflow the window, wrap, and
/// scroll — the screen then looks blank with content pushed below the fold.
///
/// All host painting goes through `host_lock`, so watcher and main-thread
/// frames never interleave. The returned stop flag ends the watcher.
pub fn spawn_render_watcher(
    model: Arc<Mutex<TerminalModel>>,
    in_command: Arc<AtomicBool>,
    host_lock: Arc<Mutex<Stdout>>,
    last_version: Arc<Mutex<u64>>,
    stop: Arc<AtomicBool>,
) {
    thread::spawn(move || {
        let mut last_known_size = model.lock().expect("model lock poisoned").size();
        let mut size_elapsed = Duration::ZERO;
        loop {
            if stop.load(Ordering::Relaxed) {
                break;
            }
            thread::sleep(RENDER_POLL);
            size_elapsed += RENDER_POLL;
            if size_elapsed >= SIZE_CHECK_POLL {
                size_elapsed = Duration::ZERO;
                if let Ok((cols, rows)) = crossterm::terminal::size()
                    && rows > 0
                    && cols > 0
                {
                    let size = Size::new(rows, cols);
                    if size != last_known_size {
                        last_known_size = size;
                        model.lock().expect("model lock poisoned").resize(size);
                        // Repaint right away so the resized frame appears
                        // even while the shell is idle.
                        let model = model.lock().expect("model lock poisoned");
                        let mut version = last_version.lock().expect("version lock poisoned");
                        if model.version() != *version
                            && let Ok(mut host) = host_lock.try_lock()
                        {
                            let _ = render(&mut host, &model, &mut version);
                        }
                        continue;
                    }
                }
            }
            if in_command.load(Ordering::Relaxed) {
                let model = model.lock().expect("model lock poisoned");
                let mut version = last_version.lock().expect("version lock poisoned");
                if model.version() != *version
                    && let Ok(mut host) = host_lock.try_lock()
                {
                    let _ = render(&mut host, &model, &mut version);
                }
            }
        }
    });
}

/// What the host key reader should do with the next key event.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum KeyDestination {
    /// The shell is idle at the prompt: the key belongs to the prompt
    /// editor.
    Prompt,
    /// A command is executing and may be polling the terminal.
    Command,
}

/// Spawns the host key reader thread.
///
/// The thread reads host events and routes them either into the virtual
/// model's key queue (while a command is running) or into a channel for the
/// prompt editor. Resize events resize the model. Returns the prompt
/// channel's sender and receiver, and the routing flag.
pub fn spawn_key_reader(
    model: Arc<Mutex<TerminalModel>>,
) -> (Sender<KeyEvent>, Receiver<KeyEvent>, Arc<AtomicBool>) {
    let (sender, receiver) = channel();
    let key_sender = sender.clone();
    let in_command = Arc::new(AtomicBool::new(false));
    let in_command_flag = Arc::clone(&in_command);
    thread::spawn(move || {
        loop {
            let Ok(event) = crossterm::event::read() else {
                continue;
            };
            match event {
                Event::Key(crossterm_key) => {
                    let destination = if in_command_flag.load(Ordering::Relaxed) {
                        KeyDestination::Command
                    } else {
                        KeyDestination::Prompt
                    };
                    forward_key(crossterm_key, destination, &model, &key_sender);
                }
                Event::Mouse(mouse) => {
                    // Scroll wheel/trackpad gestures while a pager like `man`
                    // is running. Outside a command the shell prompt handles
                    // ArrowUp/Down as history navigation, so wheel there would
                    // unexpectedly cycle history — ignore it at the prompt and
                    // only forward during a command.
                    let destination = if in_command_flag.load(Ordering::Relaxed) {
                        KeyDestination::Command
                    } else {
                        continue;
                    };
                    use crossterm::event::MouseEventKind;
                    let scroll_key = match mouse.kind {
                        MouseEventKind::ScrollUp => Some(Key::ArrowUp),
                        MouseEventKind::ScrollDown => Some(Key::ArrowDown),
                        _ => None,
                    };
                    if let Some(key) = scroll_key {
                        route_event(KeyEvent::special(key), destination, &model, &key_sender);
                    }
                }
                // crossterm reports Resize(width, height).
                Event::Resize(cols, rows) => {
                    model
                        .lock()
                        .expect("model lock poisoned")
                        .resize(Size::new(rows, cols));
                }
                _ => {}
            }
        }
    });
    (sender, receiver, in_command)
}

/// Routes one host key event to its destination.
fn forward_key(
    key: CrosstermKeyEvent,
    destination: KeyDestination,
    model: &Arc<Mutex<TerminalModel>>,
    sender: &Sender<KeyEvent>,
) {
    if let Some(event) = translate_key(&key) {
        route_event(event, destination, model, sender);
    }
}

/// Sends a virtual key event to its destination.
fn route_event(
    event: KeyEvent,
    destination: KeyDestination,
    model: &Arc<Mutex<TerminalModel>>,
    sender: &Sender<KeyEvent>,
) {
    match destination {
        KeyDestination::Command => {
            model
                .lock()
                .expect("model lock poisoned")
                .push_keys(&[event]);
        }
        KeyDestination::Prompt => {
            let _ = sender.send(event);
        }
    }
}

/// Translates a host key event directly into a virtual event.
pub(crate) fn translate_key(key: &CrosstermKeyEvent) -> Option<KeyEvent> {
    if key.kind == KeyEventKind::Release {
        return None;
    }
    let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
    let alt = key.modifiers.contains(KeyModifiers::ALT);
    let shift = key.modifiers.contains(KeyModifiers::SHIFT);
    let mut event = match key.code {
        KeyCode::Char('\n' | '\r' | 'j' | 'm')
            if ctrl || matches!(key.code, KeyCode::Char('\n' | '\r')) =>
        {
            KeyEvent::special(Key::Enter)
        }
        KeyCode::Char('\t' | 'i') if ctrl || key.code == KeyCode::Char('\t') => {
            KeyEvent::special(Key::Tab)
        }
        KeyCode::Char('\u{8}' | '\u{7f}' | 'h')
            if ctrl || matches!(key.code, KeyCode::Char('\u{8}' | '\u{7f}')) =>
        {
            KeyEvent::special(Key::Backspace)
        }
        KeyCode::Char(ch) => {
            if ctrl && (ch == 'c' || ch == 'd' || ch == 'o' || ch == 'x' || ch == 'z') {
                KeyEvent {
                    key: Key::Character,
                    character: Some(ch.to_ascii_lowercase()),
                    ctrl: true,
                    alt,
                    shift,
                }
            } else {
                KeyEvent {
                    key: Key::Character,
                    character: Some(ch),
                    ctrl,
                    alt,
                    shift,
                }
            }
        }
        KeyCode::Esc => KeyEvent::special(Key::Escape),
        KeyCode::Enter => KeyEvent::special(Key::Enter),
        KeyCode::Backspace => KeyEvent::special(Key::Backspace),
        KeyCode::Tab | KeyCode::BackTab => KeyEvent::special(Key::Tab),
        KeyCode::Up => KeyEvent::special(Key::ArrowUp),
        KeyCode::Down => KeyEvent::special(Key::ArrowDown),
        KeyCode::Left => KeyEvent::special(Key::ArrowLeft),
        KeyCode::Right => KeyEvent::special(Key::ArrowRight),
        KeyCode::Home => KeyEvent::special(Key::Home),
        KeyCode::End => KeyEvent::special(Key::End),
        KeyCode::PageUp => KeyEvent::special(Key::PageUp),
        KeyCode::PageDown => KeyEvent::special(Key::PageDown),
        KeyCode::Delete => KeyEvent::special(Key::Delete),
        KeyCode::Insert => KeyEvent::special(Key::Insert),
        KeyCode::F(n) => KeyEvent::special(Key::Function(n)),
        _ => return None,
    };
    event.ctrl = ctrl;
    event.alt = alt;
    event.shift = shift || key.code == KeyCode::BackTab;
    Some(event)
}

#[cfg(test)]
mod tests {
    use super::*;
    fn key(code: KeyCode, modifiers: KeyModifiers) -> CrosstermKeyEvent {
        CrosstermKeyEvent::new_with_kind(code, modifiers, KeyEventKind::Press)
    }

    #[test]
    fn host_characters_preserve_unicode() {
        assert_eq!(
            translate_key(&key(KeyCode::Char('a'), KeyModifiers::NONE)),
            Some(KeyEvent::character('a'))
        );
        assert_eq!(
            translate_key(&key(KeyCode::Char('é'), KeyModifiers::NONE)),
            Some(KeyEvent::character('é'))
        );
        assert_eq!(
            translate_key(&key(KeyCode::Char('🔐'), KeyModifiers::NONE)),
            Some(KeyEvent::character('🔐'))
        );
    }

    #[test]
    fn host_key_modifiers_are_not_lost() {
        let control = translate_key(&key(KeyCode::Char('c'), KeyModifiers::CONTROL)).unwrap();
        assert_eq!(control, KeyEvent::ctrl('c'));

        let shifted = translate_key(&key(KeyCode::Left, KeyModifiers::SHIFT)).unwrap();
        assert_eq!(shifted.key, Key::ArrowLeft);
        assert!(shifted.shift);

        let back_tab = translate_key(&key(KeyCode::BackTab, KeyModifiers::SHIFT)).unwrap();
        assert_eq!(back_tab.key, Key::Tab);
        assert!(back_tab.shift);
    }

    #[test]
    fn pasted_control_characters_keep_key_semantics() {
        for character in ['\n', '\r'] {
            assert_eq!(
                translate_key(&key(KeyCode::Char(character), KeyModifiers::NONE)),
                Some(KeyEvent::special(Key::Enter))
            );
        }
        assert_eq!(
            translate_key(&key(KeyCode::Char('\t'), KeyModifiers::NONE)),
            Some(KeyEvent::special(Key::Tab))
        );
        assert_eq!(
            translate_key(&key(KeyCode::Char('j'), KeyModifiers::CONTROL)),
            Some(KeyEvent {
                ctrl: true,
                ..KeyEvent::special(Key::Enter)
            })
        );
    }

    #[test]
    fn key_release_events_do_not_duplicate_input() {
        let released = CrosstermKeyEvent::new_with_kind(
            KeyCode::Char('a'),
            KeyModifiers::NONE,
            KeyEventKind::Release,
        );
        assert_eq!(translate_key(&released), None);
    }
}