aboutsummaryrefslogtreecommitdiffstats
path: root/src/bin/ttyrec/main.rs
blob: 1a3c03d497ca0f61a848e4544118c2efba92312b (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
#![warn(clippy::cargo)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]
#![warn(clippy::as_conversions)]
#![warn(clippy::get_unwrap)]
#![allow(clippy::cognitive_complexity)]
#![allow(clippy::missing_const_for_fn)]
#![allow(clippy::similar_names)]
#![allow(clippy::struct_excessive_bools)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::type_complexity)]

use clap::Parser as _;
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

#[derive(Debug, clap::Parser)]
#[command(
    name = "ttyrec",
    about = "Records ttyrec files",
    long_about = "\n\
        This program will run a shell (or other program specified by the -c \
        option), and record the full output, including timing information, \
        for later playback (such as via the included `ttyplay` command)."
)]
struct Opt {
    #[arg(
        short,
        long,
        default_value = "ttyrec",
        help = "File to save ttyrec data to"
    )]
    file: std::ffi::OsString,

    #[arg(short, long, help = "Command to run [default: $SHELL]")]
    cmd: Option<std::ffi::OsString>,
}

fn get_cmd(
    cmd: Option<std::ffi::OsString>,
) -> (std::ffi::OsString, Vec<std::ffi::OsString>) {
    cmd.map_or_else(
        || {
            let shell =
                std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into());
            (shell, vec![])
        },
        |cmd| {
            let mut exec_cmd = std::ffi::OsString::from("exec ");
            exec_cmd.push(cmd);
            ("/bin/sh".into(), vec!["-c".into(), exec_cmd])
        },
    )
}

#[derive(Debug)]
enum Event {
    Key(textmode::Result<Option<textmode::Key>>),
    Stdout(std::io::Result<Vec<u8>>),
    Resize((u16, u16)),
    Error(anyhow::Error),
    Quit,
}

#[tokio::main]
async fn async_main(opt: Opt) -> anyhow::Result<()> {
    let Opt { cmd, file } = opt;
    let (cmd, args) = get_cmd(cmd);

    let fh = tokio::fs::File::create(file).await?;

    let mut input = textmode::blocking::Input::new()?;
    let _input_guard = input.take_raw_guard();
    let mut stdout = tokio::io::stdout();

    let size = terminal_size::terminal_size().map_or(
        (24, 80),
        |(terminal_size::Width(w), terminal_size::Height(h))| (h, w),
    );
    let mut pty = pty_process::Pty::new()?;
    pty.resize(pty_process::Size::new(size.0, size.1))?;
    let pts = pty.pts()?;
    let mut child = pty_process::Command::new(cmd).args(args).spawn(&pts)?;

    let (event_w, mut event_r) = tokio::sync::mpsc::unbounded_channel();
    let (input_w, mut input_r) = tokio::sync::mpsc::unbounded_channel();
    let (resize_w, mut resize_r) = tokio::sync::mpsc::unbounded_channel();

    {
        let mut signals = tokio::signal::unix::signal(
            tokio::signal::unix::SignalKind::window_change(),
        )?;
        let event_w = event_w.clone();
        tokio::task::spawn(async move {
            while signals.recv().await.is_some() {
                event_w
                    .send(Event::Resize(
                        terminal_size::terminal_size().map_or(
                            (24, 80),
                            |(
                                terminal_size::Width(w),
                                terminal_size::Height(h),
                            )| { (h, w) },
                        ),
                    ))
                    // event_w is never closed, so this can never fail
                    .unwrap();
            }
        });
    }

    {
        let event_w = event_w.clone();
        std::thread::spawn(move || {
            loop {
                event_w
                    .send(Event::Key(input.read_key()))
                    // event_w is never closed, so this can never fail
                    .unwrap();
            }
        });
    }

    {
        let event_w = event_w.clone();
        tokio::task::spawn(async move {
            loop {
                let mut buf = [0_u8; 4096];
                tokio::select! {
                    res = pty.read(&mut buf) => {
                        let res = res.map(|n| buf[..n].to_vec());
                        let err = res.is_err();
                        event_w
                            .send(Event::Stdout(res))
                            // event_w is never closed, so this can never fail
                            .unwrap();
                        if err {
                            eprintln!("pty read failed: {}", err);
                            break;
                        }
                    }
                    res = input_r.recv() => {
                        // input_r is never closed, so this can never fail
                        let bytes: Vec<u8> = res.unwrap();
                        if let Err(e) = pty.write(&bytes).await {
                            event_w
                                .send(Event::Error(anyhow::anyhow!(e)))
                                // event_w is never closed, so this can never
                                // fail
                                .unwrap();
                        }
                    }
                    res = resize_r.recv() => {
                        // resize_r is never closed, so this can never fail
                        let size: (u16, u16) = res.unwrap();
                        if let Err(e) = pty.resize(
                            pty_process::Size::new(size.0, size.1),
                        ) {
                            event_w
                                .send(Event::Error(anyhow::anyhow!(e)))
                                // event_w is never closed, so this can never
                                // fail
                                .unwrap();
                        }
                    }
                    _ = child.wait() => {
                        event_w.send(Event::Quit).unwrap();
                        break;
                    }
                }
            }
        });
    }

    let mut writer = ttyrec::Writer::new(fh);
    loop {
        // XXX unwrap
        match event_r.recv().await.unwrap() {
            Event::Key(key) => {
                let key = key?;
                if let Some(key) = key {
                    input_w.send(key.into_bytes()).unwrap();
                } else {
                    break;
                }
            }
            Event::Stdout(bytes) => match bytes {
                Ok(bytes) => {
                    writer.frame(&bytes).await?;
                    stdout.write_all(&bytes).await?;
                    stdout.flush().await?;
                }
                Err(e) => {
                    anyhow::bail!("failed to read from child process: {}", e);
                }
            },
            Event::Resize((h, w)) => {
                resize_w.send((h, w)).unwrap();
            }
            Event::Error(e) => {
                return Err(e);
            }
            Event::Quit => break,
        }
    }

    Ok(())
}

fn main() {
    let opt = Opt::parse();
    match async_main(opt) {
        Ok(_) => (),
        Err(e) => {
            eprintln!("ttyrec: {}", e);
            std::process::exit(1);
        }
    };
}