summaryrefslogtreecommitdiffstats
path: root/src/history.rs
blob: 348224bbf0c2c9fa280d301b97404b19a526a044 (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
use async_std::io::{ReadExt as _, WriteExt as _};
use pty_process::Command as _;
use textmode::Textmode as _;

pub struct History {
    entries: Vec<crate::util::Mutex<HistoryEntry>>,
    action: async_std::channel::Sender<crate::action::Action>,
}

impl History {
    pub fn new(
        action: async_std::channel::Sender<crate::action::Action>,
    ) -> Self {
        Self {
            entries: vec![],
            action,
        }
    }

    pub async fn run(&mut self, cmd: &str) -> anyhow::Result<usize> {
        let (exe, args) = parse_cmd(cmd);
        let mut process = async_std::process::Command::new(&exe);
        process.args(&args);
        let child = process
            .spawn_pty(Some(&pty_process::Size::new(24, 80)))
            .unwrap();
        let (input_w, input_r) = async_std::channel::unbounded();
        let entry = crate::util::mutex(HistoryEntry::new(
            cmd,
            child.id().try_into().unwrap(),
            input_w,
        ));
        let task_entry = async_std::sync::Arc::clone(&entry);
        let task_action = self.action.clone();
        async_std::task::spawn(async move {
            loop {
                enum Res {
                    Read(Result<usize, std::io::Error>),
                    Write(Result<Vec<u8>, async_std::channel::RecvError>),
                }
                let mut buf = [0_u8; 4096];
                let mut pty = child.pty();
                let read = async { Res::Read(pty.read(&mut buf).await) };
                let write = async { Res::Write(input_r.recv().await) };
                match futures_lite::future::race(read, write).await {
                    Res::Read(res) => {
                        match res {
                            Ok(bytes) => {
                                task_entry
                                    .lock_arc()
                                    .await
                                    .vt
                                    .process(&buf[..bytes]);
                            }
                            Err(e) => {
                                if e.raw_os_error() != Some(libc::EIO) {
                                    eprintln!("pty read failed: {:?}", e);
                                }
                                task_entry.lock_arc().await.running = false;
                                task_action
                                    .send(crate::action::Action::UpdateFocus(
                                        crate::state::Focus::Readline,
                                    ))
                                    .await
                                    .unwrap();
                                break;
                            }
                        }
                        task_action
                            .send(crate::action::Action::Render)
                            .await
                            .unwrap();
                    }
                    Res::Write(res) => match res {
                        Ok(bytes) => {
                            pty.write(&bytes).await.unwrap();
                        }
                        Err(e) => {
                            panic!(
                                "failed to read from input channel: {}",
                                e
                            );
                        }
                    },
                }
            }
        });
        self.entries.push(entry);
        self.action
            .send(crate::action::Action::UpdateFocus(
                crate::state::Focus::History(self.entries.len() - 1),
            ))
            .await
            .unwrap();
        Ok(self.entries.len() - 1)
    }

    pub async fn handle_key(
        &mut self,
        key: textmode::Key,
        idx: usize,
    ) -> bool {
        match key {
            textmode::Key::Ctrl(b'c') => {
                let pid = self.entries[idx].lock_arc().await.pid;
                nix::sys::signal::kill(pid, nix::sys::signal::Signal::SIGINT)
                    .unwrap();
            }
            textmode::Key::Ctrl(b'z') => {
                self.action
                    .send(crate::action::Action::UpdateFocus(
                        crate::state::Focus::Readline,
                    ))
                    .await
                    .unwrap();
            }
            key => {
                self.send_process_input(idx, &key.into_bytes())
                    .await
                    .unwrap();
            }
        }
        false
    }

    pub async fn render(
        &self,
        out: &mut textmode::Output,
        repl_lines: usize,
        focus: Option<usize>,
    ) -> anyhow::Result<()> {
        let mut used_lines = repl_lines;
        let mut pos = None;
        for (idx, entry) in self.entries.iter().enumerate().rev() {
            let entry = entry.lock_arc().await;
            let screen = entry.vt.screen();
            let mut last_row = 0;
            for (idx, row) in screen.rows(0, 80).enumerate() {
                if !row.is_empty() {
                    last_row = idx + 1;
                }
            }
            if focus == Some(idx) {
                last_row = std::cmp::max(
                    last_row,
                    screen.cursor_position().0 as usize + 1,
                );
            }
            used_lines += 1 + std::cmp::min(6, last_row);
            if used_lines > 24 {
                break;
            }
            if used_lines == 1 {
                used_lines = 2;
                pos = Some((23, 0));
            }
            out.move_to((24 - used_lines).try_into().unwrap(), 0);
            out.write_str("$ ");
            if entry.running {
                out.set_bgcolor(vt100::Color::Rgb(16, 64, 16));
            }
            out.write_str(&entry.cmd);
            out.reset_attributes();
            if last_row > 5 {
                out.write(b"\r\n");
                out.set_bgcolor(textmode::color::RED);
                out.write(b"...");
                out.reset_attributes();
            }
            let mut end_pos = (0, 0);
            for row in screen
                .rows_formatted(0, 80)
                .take(last_row)
                .skip(last_row.saturating_sub(5))
            {
                out.write(b"\r\n");
                out.write(&row);
                end_pos = out.screen().cursor_position();
            }
            if pos.is_none() {
                pos = Some(end_pos);
            }
            out.reset_attributes();
        }
        if let Some(pos) = pos {
            out.move_to(pos.0, pos.1);
        }
        Ok(())
    }

    async fn send_process_input(
        &self,
        idx: usize,
        input: &[u8],
    ) -> anyhow::Result<()> {
        self.entries[idx]
            .lock_arc()
            .await
            .input
            .send(input.to_vec())
            .await
            .unwrap();
        Ok(())
    }
}

struct HistoryEntry {
    cmd: String,
    pid: nix::unistd::Pid,
    vt: vt100::Parser,
    input: async_std::channel::Sender<Vec<u8>>,
    running: bool, // option end time
                   // start time
}

impl HistoryEntry {
    fn new(
        cmd: &str,
        pid: i32,
        input: async_std::channel::Sender<Vec<u8>>,
    ) -> Self {
        Self {
            cmd: cmd.into(),
            pid: nix::unistd::Pid::from_raw(pid),
            vt: vt100::Parser::new(24, 80, 0),
            input,
            running: true,
        }
    }
}

fn parse_cmd(full_cmd: &str) -> (String, Vec<String>) {
    let mut parts = full_cmd.split(' ');
    let cmd = parts.next().unwrap();
    (
        cmd.to_string(),
        parts.map(std::string::ToString::to_string).collect(),
    )
}