small software-rendered rust tty
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
#![feature(deadline_api)]
use std::io::Write;
use std::iter::successors;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::process::{Command, exit};
use std::sync::mpsc;
use std::thread::sleep;
use std::time::Duration;

use anyhow::Result;
use minifb::{InputCallback, Key, WindowOptions};
use nix::pty::{ForkptyResult, forkpty};

fn spawn(shell: &str) -> Result<OwnedFd> {
    let x = unsafe { forkpty(None, None)? };
    match x {
        ForkptyResult::Child => {
            let sh = Command::new(shell).spawn()?.wait();
            // std::thread::sleep(Duration::from_millis(5000));
            // exit(0);

            exit(0);
        }
        ForkptyResult::Parent { child, master } => {
            use libc::{F_GETFL, F_SETFL, O_NONBLOCK, fcntl};
            unsafe {
                assert_eq!(
                    fcntl(
                        master.as_raw_fd(),
                        F_SETFL,
                        fcntl(master.as_raw_fd(), F_GETFL, 0) | O_NONBLOCK,
                    ),
                    0
                )
            };
            Ok(master)
        }
    }
}

fn read(fd: BorrowedFd) -> Option<Vec<u8>> {
    let mut x = [0; 1 << 16];
    let n = nix::unistd::read(fd, &mut x).ok()?;
    Some(x[..n].to_vec())
}
fn write(fd: BorrowedFd, x: &[u8]) -> Result<()> {
    let n = nix::unistd::write(fd, x)?;
    anyhow::ensure!(n == x.len());
    Ok(())
}

struct KeyPress(mpsc::Sender<Key>);
impl InputCallback for KeyPress {
    fn add_char(&mut self, _: u32) {}
    fn set_key_state(&mut self, key: Key, state: bool) {
        if state {
            self.0.send((key)).unwrap();
        }
    }
}
enum Event {
    Read(Vec<u8>),
    Write(Key),
}
fn main() -> Result<()> {
    let mut w = minifb::Window::new(
        "pattypan",
        5,
        5,
        WindowOptions {
            borderless: true,
            title: false,
            resize: true,
            ..Default::default()
        },
    )?;

    // input
    let (ktx, krx) = mpsc::channel::<Key>();

    w.set_input_callback(Box::new(KeyPress(ktx)));
    w.update();

    let pty = spawn("fish")?;
    let pty1 = pty.try_clone()?;

    std::thread::spawn(move || {
        while let Ok(k) = krx.recv() {
            let x = match k {
                Key::Enter => b"\n",
                Key::Space => b" ",
                _ => &[k as u8 - 10 + b'a'],
            };
            write(pty1.as_fd(), x).unwrap();
        }
    });

    // output
    let (ttx, trx) = mpsc::channel();

    std::thread::spawn(move || {
        loop {
            let x = successors(read(pty.as_fd()), |_| read(pty.as_fd()))
                .flatten()
                .collect::<Vec<u8>>();
            if !x.is_empty() {
                // println!("recv");
                ttx.send(x).unwrap();
            }
            sleep(Duration::from_millis(10))
        }
    });

    // let x = b"echo -e \"\x1b(0lqqqk\nx   \x1b(Bx\nmqqqj";
    // let x = String::from_utf8_lossy(&x);
    // println!("{}", x);
    let mut s = anstream::StripStream::new(std::io::stdout());
    loop {
        while let Ok(x) = trx.recv_timeout(Duration::from_millis(50)) {
            s.write_all(&x)?;
        }
        s.flush()?;
        w.update();
        sleep(Duration::from_millis(10))
    }

    // println!("-------------------");
    // let mut t = TerminalInputParser::new();
    // for char in x {
    //     use ctlfun::TerminalInput::*;
    //     match t.parse_byte(char) {
    //         Continue => {
    //             print!("-");
    //         }
    //         Char(x) => print!("{x}"),
    //         Control(control_function) => println!("{:?}", control_function),
    //         _ => panic!(),
    //     }
    // }

    Ok(())
}