aboutsummaryrefslogtreecommitdiffstats
path: root/src/tui.rs
blob: 766f5ad3b14ec8bd89e3cfb28f0670f582ef275c (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
use futures::future::Future as _;
use futures::stream::Stream as _;
use snafu::{OptionExt as _, ResultExt as _};
use std::io::Write as _;

#[derive(Debug, snafu::Snafu)]
enum Error {
    #[snafu(display("invalid command index: {}", idx))]
    InvalidCommandIndex { idx: usize },

    #[snafu(display(
        "failed to put the terminal into raw mode: {}",
        source
    ))]
    IntoRawMode { source: crossterm::ErrorKind },

    #[snafu(display("error during read: {}", source))]
    Read { source: crate::readline::Error },

    #[snafu(display("error during eval: {}", source))]
    Eval { source: crate::eval::Error },

    #[snafu(display("error during print: {}", source))]
    Print { source: std::io::Error },

    #[snafu(display("eof"))]
    EOF,
}

type Result<T> = std::result::Result<T, Error>;

pub fn tui() {
    tokio::run(Tui::new());
}

#[derive(Default)]
pub struct Tui {
    idx: usize,
    readline: Option<crate::readline::Readline>,
    commands: std::collections::HashMap<usize, Command>,
    raw_screen: Option<crossterm::screen::RawScreen>,
}

impl Tui {
    pub fn new() -> Self {
        Self::default()
    }

    fn read() -> crate::readline::Readline {
        crate::readline::Readline::new().set_raw(false)
    }

    fn eval(
        &mut self,
        idx: usize,
        line: &str,
    ) -> std::result::Result<(), Error> {
        if self.commands.contains_key(&idx) {
            return Err(Error::InvalidCommandIndex { idx });
        }
        let eval = crate::eval::Eval::new(line).set_raw(false);
        self.commands.insert(idx, Command::new(eval));
        Ok(())
    }

    fn print(
        &mut self,
        idx: usize,
        event: tokio_pty_process_stream::Event,
    ) -> Result<()> {
        match event {
            tokio_pty_process_stream::Event::CommandStart { cmd, args } => {
                self.command_start(idx, &cmd, &args)
            }
            tokio_pty_process_stream::Event::Output { data: out } => {
                self.command_output(idx, &out)
            }
            tokio_pty_process_stream::Event::CommandExit { status } => {
                self.command_exit(idx, status)
            }
            tokio_pty_process_stream::Event::Resize { size } => {
                self.command_resize(idx, size)
            }
        }
    }

    fn command_start(
        &mut self,
        idx: usize,
        cmd: &str,
        args: &[String],
    ) -> Result<()> {
        let command = self
            .commands
            .get_mut(&idx)
            .context(InvalidCommandIndex { idx })?;
        let cmd = cmd.to_string();
        let args = args.to_vec();
        command.cmd = Some(cmd);
        command.args = Some(args);
        Ok(())
    }

    fn command_output(&mut self, idx: usize, output: &[u8]) -> Result<()> {
        let command = self
            .commands
            .get_mut(&idx)
            .context(InvalidCommandIndex { idx })?;
        command.output.append(&mut output.to_vec());

        let stdout = std::io::stdout();
        let mut stdout = stdout.lock();
        stdout.write(output).context(Print)?;
        stdout.flush().context(Print)?;

        Ok(())
    }

    fn command_exit(
        &mut self,
        idx: usize,
        status: std::process::ExitStatus,
    ) -> Result<()> {
        let command = self
            .commands
            .get_mut(&idx)
            .context(InvalidCommandIndex { idx })?;
        command.status = Some(status);
        Ok(())
    }

    fn command_resize(
        &mut self,
        _idx: usize,
        _size: (u16, u16),
    ) -> Result<()> {
        // TODO
        Ok(())
    }

    fn poll_read(&mut self) {
        if self.readline.is_none() && self.commands.is_empty() {
            self.idx += 1;
            self.readline = Some(Self::read())
        }
    }

    fn poll_eval(&mut self) -> Result<bool> {
        if let Some(mut r) = self.readline.take() {
            match r.poll() {
                Ok(futures::Async::Ready(line)) => {
                    match self.eval(self.idx, &line) {
                        Ok(())
                        | Err(Error::Eval {
                            source:
                                crate::eval::Error::Parser {
                                    source:
                                        crate::parser::Error::CommandRequired,
                                    ..
                                },
                        }) => {}
                        Err(e) => return Err(e),
                    }
                    Ok(true)
                }
                Ok(futures::Async::NotReady) => {
                    self.readline.replace(r);
                    Ok(false)
                }
                Err(crate::readline::Error::EOF) => Err(Error::EOF),
                Err(e) => Err(e).context(Read),
            }
        } else {
            Ok(false)
        }
    }

    fn poll_print(&mut self) -> Result<bool> {
        let mut did_work = false;

        for idx in self.commands.keys().cloned().collect::<Vec<usize>>() {
            match self.commands.get_mut(&idx).unwrap().future.poll() {
                Ok(futures::Async::Ready(Some(event))) => {
                    self.print(idx, event)?;
                    did_work = true;
                }
                Ok(futures::Async::Ready(None)) => {
                    self.commands
                        .remove(&idx)
                        .context(InvalidCommandIndex { idx })?;
                    did_work = true;
                }
                Ok(futures::Async::NotReady) => {}

                // Parser and Command errors are always fatal, but execution
                // errors might not be
                Err(e @ crate::eval::Error::Parser { .. }) => {
                    self.commands
                        .remove(&idx)
                        .context(InvalidCommandIndex { idx })?;
                    return Err(e).context(Eval);
                }
                Err(e @ crate::eval::Error::Command { .. }) => {
                    self.commands
                        .remove(&idx)
                        .context(InvalidCommandIndex { idx })?;
                    return Err(e).context(Eval);
                }
                Err(e) => {
                    return Err(e).context(Eval);
                }
            }
        }

        Ok(did_work)
    }

    fn poll_with_errors(&mut self) -> futures::Poll<(), Error> {
        if self.raw_screen.is_none() {
            self.raw_screen = Some(
                crossterm::screen::RawScreen::into_raw_mode()
                    .context(IntoRawMode)?,
            );
        }

        loop {
            let mut did_work = false;

            self.poll_read();
            did_work |= self.poll_eval()?;
            did_work |= self.poll_print()?;

            if !did_work {
                return Ok(futures::Async::NotReady);
            }
        }
    }
}

impl futures::future::Future for Tui {
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> futures::Poll<Self::Item, Self::Error> {
        loop {
            match self.poll_with_errors() {
                Ok(a) => return Ok(a),
                Err(Error::EOF) => return Ok(futures::Async::Ready(())),
                Err(e) => {
                    eprint!("error polling state: {}\r\n", e);
                }
            }
        }
    }
}

struct Command {
    future: crate::eval::Eval,
    cmd: Option<String>,
    args: Option<Vec<String>>,
    output: Vec<u8>,
    status: Option<std::process::ExitStatus>,
}

impl Command {
    fn new(future: crate::eval::Eval) -> Self {
        Self {
            future,
            cmd: None,
            args: None,
            output: vec![],
            status: None,
        }
    }
}