aboutsummaryrefslogtreecommitdiffstats
path: root/examples/tmux.rs
blob: eaff4c4725213f4204a3b8300f7e9211b9647f2b (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
use pty_process::Command as _;
use smol::io::{AsyncReadExt as _, AsyncWriteExt as _};
use std::os::unix::io::AsRawFd as _;
use textmode::TextmodeExt as _;

pub struct RawGuard {
    termios: nix::sys::termios::Termios,
}

#[allow(clippy::new_without_default)]
impl RawGuard {
    pub fn new() -> Self {
        let stdin = std::io::stdin().as_raw_fd();
        let termios = nix::sys::termios::tcgetattr(stdin).unwrap();
        let mut termios_raw = termios.clone();
        nix::sys::termios::cfmakeraw(&mut termios_raw);
        nix::sys::termios::tcsetattr(
            stdin,
            nix::sys::termios::SetArg::TCSANOW,
            &termios_raw,
        )
        .unwrap();
        Self { termios }
    }
}

impl Drop for RawGuard {
    fn drop(&mut self) {
        let stdin = std::io::stdin().as_raw_fd();
        let _ = nix::sys::termios::tcsetattr(
            stdin,
            nix::sys::termios::SetArg::TCSANOW,
            &self.termios,
        );
    }
}

enum Command {
    NewWindow,
    NextWindow,
}

enum Event {
    Input(Vec<u8>),
    Output,
    WindowExit(usize),
    Command(Command),
}

struct Window {
    child: std::sync::Arc<pty_process::smol::Child>,
    vt: std::sync::Arc<smol::lock::Mutex<vt100::Parser>>,
    screen: vt100::Screen,
}

struct State {
    windows: std::collections::BTreeMap<usize, Window>,
    current_window: usize,
    next_window_id: usize,
    wevents: smol::channel::Sender<Event>,
    revents: smol::channel::Receiver<Event>,
}

impl State {
    fn new() -> Self {
        let (sender, receiver) = smol::channel::unbounded();
        Self {
            windows: std::collections::BTreeMap::new(),
            current_window: 0,
            next_window_id: 0,
            wevents: sender,
            revents: receiver,
        }
    }

    fn current_window(&self) -> &Window {
        &self.windows[&self.current_window]
    }

    fn current_window_mut(&mut self) -> &mut Window {
        self.windows.get_mut(&self.current_window).unwrap()
    }

    fn next_window(&mut self) {
        self.current_window = self
            .windows
            .keys()
            .copied()
            .cycle()
            .skip_while(|&id| id < self.current_window)
            .nth(1)
            .unwrap();
    }

    fn spawn_input_task(&self, ex: &smol::Executor<'_>) {
        let notify = self.wevents.clone();
        ex.spawn(async move {
            let mut waiting_for_command = false;
            let mut stdin = smol::Unblock::new(std::io::stdin());
            let mut buf = [0u8; 4096];
            loop {
                match stdin.read(&mut buf).await {
                    Ok(bytes) => {
                        waiting_for_command = Self::handle_input(
                            &buf[..bytes],
                            notify.clone(),
                            waiting_for_command,
                        )
                        .await;
                    }
                    Err(e) => {
                        eprintln!("{}", e);
                        break;
                    }
                }
            }
        })
        .detach();
    }

    async fn new_window(
        &mut self,
        ex: &smol::Executor<'_>,
        notify: smol::channel::Sender<Event>,
    ) {
        let child = smol::process::Command::new("zsh")
            .spawn_pty(Some(&pty_process::Size::new(24, 80)))
            .unwrap();
        let child = std::sync::Arc::new(child);
        let vt = vt100::Parser::new(24, 80, 0);
        let screen = vt.screen().clone();
        let vt = std::sync::Arc::new(smol::lock::Mutex::new(vt));
        let id = self.next_window_id;
        self.next_window_id += 1;
        let window = Window {
            child: child.clone(),
            vt: vt.clone(),
            screen,
        };
        self.windows.insert(id, window);
        self.current_window = id;
        ex.spawn(async move {
            let mut buf = [0_u8; 4096];
            loop {
                match child.pty().read(&mut buf).await {
                    Ok(bytes) => {
                        vt.lock_arc().await.process(&buf[..bytes]);
                        notify.send(Event::Output).await.unwrap();
                    }
                    Err(e) => {
                        // EIO means that the process closed the other
                        // end of the pty
                        if e.raw_os_error() != Some(libc::EIO) {
                            eprintln!("pty read failed: {:?}", e);
                        }
                        notify.send(Event::WindowExit(id)).await.unwrap();
                        break;
                    }
                }
            }
        })
        .detach();
    }

    async fn handle_input(
        buf: &[u8],
        notify: smol::channel::Sender<Event>,
        mut waiting_for_command: bool,
    ) -> bool {
        let bytes = buf.len();
        let mut real_buf = Vec::with_capacity(bytes);
        for &c in buf {
            if waiting_for_command {
                match c {
                    // ^N
                    14 => {
                        real_buf.push(c);
                    }
                    // c
                    99 => {
                        notify
                            .send(Event::Command(Command::NewWindow))
                            .await
                            .unwrap();
                    }
                    // n
                    110 => {
                        notify
                            .send(Event::Command(Command::NextWindow))
                            .await
                            .unwrap();
                    }
                    _ => {}
                }
                waiting_for_command = false;
            } else {
                match c {
                    // ^N
                    14 => {
                        if !real_buf.is_empty() {
                            notify
                                .send(Event::Input(real_buf.clone()))
                                .await
                                .unwrap();
                            real_buf.clear();
                        }
                        waiting_for_command = true;
                    }
                    _ => {
                        real_buf.push(c);
                    }
                }
            }
        }
        if !real_buf.is_empty() {
            notify.send(Event::Input(real_buf.clone())).await.unwrap();
        }
        return waiting_for_command;
    }

    async fn redraw_current_window(&self, tm: &mut textmode::Textmode) {
        let window = self.current_window();
        tm.clear();
        tm.write(&window.vt.lock_arc().await.screen().contents_formatted());
        tm.refresh().await.unwrap();
    }

    async fn update_current_window(&mut self, tm: &mut textmode::Textmode) {
        let window = self.current_window_mut();
        let new_screen = window.vt.lock_arc().await.screen().clone();
        let diff = new_screen.contents_diff(&window.screen);
        tm.write(&diff);
        tm.refresh().await.unwrap();
        window.screen = new_screen;
    }
}

#[must_use]
struct Tmux {
    _raw: RawGuard,
    tm: textmode::Textmode,
    state: State,
}

impl Tmux {
    async fn new() -> Self {
        let _raw = RawGuard::new();
        let tm = textmode::Textmode::new().await.unwrap();
        let state = State::new();
        Self { _raw, tm, state }
    }

    async fn run(self, ex: &smol::Executor<'_>) {
        let Self {
            _raw,
            mut tm,
            mut state,
        } = self;

        state.new_window(ex, state.wevents.clone()).await;
        state.spawn_input_task(ex);

        ex.run(async {
            loop {
                match state.revents.recv().await {
                    Ok(Event::Output) => {
                        state.update_current_window(&mut tm).await;
                    }
                    Ok(Event::Input(buf)) => {
                        state
                            .current_window()
                            .child
                            .pty()
                            .write_all(&buf)
                            .await
                            .unwrap();
                    }
                    Ok(Event::WindowExit(id)) => {
                        let mut dropped_window =
                            state.windows.remove(&id).unwrap();
                        // i can get_mut because at this point the future
                        // holding the other copy of child has already been
                        // dropped
                        std::sync::Arc::get_mut(&mut dropped_window.child)
                            .unwrap()
                            .status()
                            .await
                            .unwrap();
                        if state.windows.is_empty() {
                            break;
                        }
                        if state.current_window == id {
                            state.next_window()
                        }

                        state.redraw_current_window(&mut tm).await;
                    }
                    Ok(Event::Command(c)) => match c {
                        Command::NewWindow => {
                            state
                                .new_window(&ex, state.wevents.clone())
                                .await;
                            state.redraw_current_window(&mut tm).await;
                        }
                        Command::NextWindow => {
                            state.next_window();
                            state.redraw_current_window(&mut tm).await;
                        }
                    },
                    Err(e) => {
                        eprintln!("{}", e);
                        break;
                    }
                }
            }
        })
        .await;

        tm.cleanup().await.unwrap();
    }
}

async fn async_main(ex: &smol::Executor<'_>) {
    let tmux = Tmux::new().await;
    tmux.run(&ex).await;
}

fn main() {
    let ex = smol::Executor::new();
    smol::block_on(async { async_main(&ex).await })
}