aboutsummaryrefslogtreecommitdiffstats
path: root/examples/interhack.rs
blob: 212c12e610299a06db0bc5bfb0c94fcbbb2d2062 (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
mod raw_guard;

#[cfg(feature = "async")]
mod main {
    use smol::io::{AsyncReadExt as _, AsyncWriteExt as _};

    pub async fn run(
        child: &async_process::Child,
        pty: &pty_process::Pty,
    ) -> std::result::Result<(), Box<dyn std::error::Error>> {
        let _raw = super::raw_guard::RawGuard::new();

        let mut input_pty = pty;
        let mut output_pty = pty;
        let ex = smol::Executor::new();

        let input = ex.spawn(async {
            let mut buf = [0_u8; 4096];
            let mut stdin = smol::Unblock::new(std::io::stdin());
            loop {
                match stdin.read(&mut buf).await {
                    Ok(bytes) => {
                        // engrave Elbereth with ^E
                        if buf[..bytes].contains(&5u8) {
                            for byte in buf[..bytes].iter() {
                                match byte {
                                    5u8 => input_pty
                                        .write_all(b"E-  Elbereth\n")
                                        .await
                                        .unwrap(),
                                    _ => input_pty
                                        .write_all(&[*byte])
                                        .await
                                        .unwrap(),
                                }
                            }
                        } else {
                            input_pty.write_all(&buf[..bytes]).await.unwrap();
                        }
                    }
                    Err(e) => {
                        eprintln!("stdin read failed: {:?}", e);
                        break;
                    }
                }
            }
        });
        let output = ex.spawn(async {
            let mut buf = [0_u8; 4096];
            let mut stdout = smol::Unblock::new(std::io::stdout());
            #[allow(clippy::trivial_regex)]
            let re = regex::bytes::Regex::new("Elbereth").unwrap();
            loop {
                match output_pty.read(&mut buf).await {
                    Ok(bytes) => {
                        // highlight successful Elbereths
                        if re.is_match(&buf[..bytes]) {
                            stdout
                                .write_all(&re.replace_all(
                                    &buf[..bytes],
                                    &b"\x1b[35m$0\x1b[m"[..],
                                ))
                                .await
                                .unwrap();
                        } else {
                            stdout.write_all(&buf[..bytes]).await.unwrap();
                        }
                        stdout.flush().await.unwrap();
                    }
                    Err(e) => {
                        eprintln!("pty read failed: {:?}", e);
                        break;
                    }
                }
            }
        });

        let wait = async {
            child.status_no_drop().await.unwrap();
        };

        ex.run(smol::future::or(smol::future::or(input, output), wait))
            .await;

        Ok(())
    }
}

#[cfg(feature = "async")]
fn main() {
    use std::os::unix::process::ExitStatusExt as _;

    let (w, h) = if let Some((w, h)) = term_size::dimensions() {
        (w as u16, h as u16)
    } else {
        (80, 24)
    };
    let status = smol::block_on(async {
        let pty = pty_process::Pty::new().unwrap();
        pty.resize(pty_process::Size::new(h, w)).unwrap();
        let mut child =
            pty_process::Command::new("nethack").spawn(&pty).unwrap();
        main::run(&child, &pty).await.unwrap();
        child.status().await.unwrap()
    });
    std::process::exit(
        status
            .code()
            .unwrap_or_else(|| status.signal().unwrap_or(0) + 128),
    );
}

#[cfg(not(feature = "async"))]
fn main() {
    unimplemented!()
}