Skip to main content

hyprstream_core/tui/
process.rs

1//! PaneProcess — connects byte-producing processes to multiplexer panes.
2//!
3//! Provides a `PaneProcess` handle that represents a running application
4//! connected to a pane via channels. The frame loop polls `stdout_rx`
5//! for output bytes and feeds them through `PanePerformer`, and routes
6//! input bytes through `input_tx`.
7
8use std::io::{self, Write};
9
10use tokio::sync::mpsc;
11use waxterm::app::{TerminalApp, TerminalConfig};
12use waxterm::backend::AnsiBackend;
13use waxterm::input::InputParser;
14
15/// Commands from the multiplexer to a hosted process.
16pub enum ProcessInput {
17    /// Raw bytes to deliver as stdin.
18    Stdin(Vec<u8>),
19    /// Pane was resized.
20    Resize { cols: u16, rows: u16 },
21    /// Kill the process.
22    Kill,
23}
24
25/// A byte source connected to a pane.
26///
27/// The frame loop polls `stdout_rx` for ANSI output bytes and feeds them
28/// through `PanePerformer::feed()`. Input from the viewer is sent through
29/// `input_tx`.
30pub struct PaneProcess {
31    pub stdout_rx: mpsc::Receiver<Vec<u8>>,
32    pub input_tx: mpsc::Sender<ProcessInput>,
33}
34
35/// A `Write` sink that sends bytes through a sync mpsc channel.
36struct ChannelWriter {
37    tx: std::sync::mpsc::SyncSender<Vec<u8>>,
38    buf: Vec<u8>,
39}
40
41impl ChannelWriter {
42    fn new(tx: std::sync::mpsc::SyncSender<Vec<u8>>) -> Self {
43        Self {
44            tx,
45            buf: Vec::with_capacity(4096),
46        }
47    }
48}
49
50impl Write for ChannelWriter {
51    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
52        self.buf.extend_from_slice(data);
53        Ok(data.len())
54    }
55
56    fn flush(&mut self) -> io::Result<()> {
57        if !self.buf.is_empty() {
58            let data = std::mem::take(&mut self.buf);
59            self.tx
60                .send(data)
61                .map_err(|_| io::Error::new(io::ErrorKind::BrokenPipe, "receiver dropped"))?;
62        }
63        Ok(())
64    }
65}
66
67impl Drop for ChannelWriter {
68    fn drop(&mut self) {
69        let _ = self.flush();
70    }
71}
72
73/// Spawn a PTY shell as a `PaneProcess`.
74///
75/// The shell's raw output bytes flow directly through `PaneProcess.stdout_rx`
76/// to the frame loop, which feeds them via `PanePerformer` (VTE parser) into
77/// the pane cell buffer. Input is routed from the frame loop to the PTY stdin.
78///
79/// This avoids double VTE parsing: only `PanePerformer` parses the PTY output.
80#[cfg(not(target_os = "wasi"))]
81pub fn spawn_pty_process(
82    cwd: Option<std::path::PathBuf>,
83    cols: u16,
84    rows: u16,
85) -> std::io::Result<PaneProcess> {
86    use hyprstream_tui::shell::{spawn_shell, ShellInput};
87
88    let shell = spawn_shell(cwd, cols, rows)?;
89
90    let (stdout_async_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(64);
91    let (input_tx, mut input_rx) = mpsc::channel::<ProcessInput>(64);
92
93    // Bridge sync PTY stdout → async tokio channel
94    let pty_stdout = shell.stdout_rx;
95    std::thread::spawn(move || {
96        while let Ok(data) = pty_stdout.recv() {
97            if stdout_async_tx.blocking_send(data).is_err() {
98                break;
99            }
100        }
101    });
102
103    // Route async ProcessInput → sync PTY stdin
104    let pty_input = shell.input_tx;
105    tokio::spawn(async move {
106        while let Some(input) = input_rx.recv().await {
107            match input {
108                ProcessInput::Stdin(data) => {
109                    let _ = pty_input.send(ShellInput::Bytes(data));
110                }
111                ProcessInput::Resize { cols, rows } => {
112                    let _ = pty_input.send(ShellInput::Resize { cols, rows });
113                }
114                ProcessInput::Kill => {
115                    let _ = pty_input.send(ShellInput::Kill);
116                    break;
117                }
118            }
119        }
120    });
121
122    Ok(PaneProcess {
123        stdout_rx,
124        input_tx,
125    })
126}
127
128/// Spawn a `TerminalApp` in a background thread, returning a `PaneProcess`
129/// handle that the frame loop can use to exchange bytes with the app.
130///
131/// The app renders into an `AnsiBackend` whose output is sent through
132/// the stdout channel. Input is received through the input channel and
133/// dispatched to the app's `handle_input`.
134pub fn spawn_app_process<A>(app: A, config: TerminalConfig) -> PaneProcess
135where
136    A: TerminalApp + Send + 'static,
137    A::Command: Send + 'static,
138{
139    let (stdout_sync_tx, stdout_sync_rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(64);
140    let (input_tx, input_rx) = mpsc::channel::<ProcessInput>(64);
141
142    // Bridge from std sync channel to tokio async channel
143    let (stdout_tx, stdout_rx) = mpsc::channel::<Vec<u8>>(64);
144
145    std::thread::spawn({
146        let stdout_tx = stdout_tx;
147        move || {
148            while let Ok(data) = stdout_sync_rx.recv() {
149                if stdout_tx.blocking_send(data).is_err() {
150                    break;
151                }
152            }
153        }
154    });
155
156    std::thread::spawn(move || {
157        run_app_loop(app, config, stdout_sync_tx, input_rx);
158    });
159
160    PaneProcess {
161        stdout_rx,
162        input_tx,
163    }
164}
165
166/// Run the app event loop on the current thread.
167fn run_app_loop<A>(
168    mut app: A,
169    config: TerminalConfig,
170    stdout_tx: std::sync::mpsc::SyncSender<Vec<u8>>,
171    mut input_rx: mpsc::Receiver<ProcessInput>,
172) where
173    A: TerminalApp,
174{
175    let writer = ChannelWriter::new(stdout_tx);
176    let backend = AnsiBackend::new(writer, config.cols, config.rows, false);
177    let mut terminal = match ratatui::Terminal::new(backend) {
178        Ok(t) => t,
179        Err(_) => return,
180    };
181
182    let parser = InputParser::new(app.input_extensions());
183
184    // Initial hide cursor + clear screen
185    let _ = terminal.hide_cursor();
186    let _ = terminal.clear();
187
188    let frame_ms = 1000u64 / u64::from(config.fps);
189    let mut needs_redraw = true;
190    let mut last_tick = std::time::Instant::now();
191
192    loop {
193        if needs_redraw {
194            if terminal.draw(|frame| app.render(frame)).is_err() {
195                break;
196            }
197            needs_redraw = false;
198        }
199
200        std::thread::sleep(std::time::Duration::from_millis(frame_ms));
201
202        let now = std::time::Instant::now();
203        let delta_ms = now.duration_since(last_tick).as_millis() as u64;
204        last_tick = now;
205
206        // Poll input (non-blocking)
207        while let Ok(input) = input_rx.try_recv() {
208            match input {
209                ProcessInput::Stdin(data) => {
210                    let cmds = parser.parse(&data);
211                    for cmd in cmds {
212                        if app.handle_input(cmd) {
213                            needs_redraw = true;
214                        }
215                    }
216                }
217                ProcessInput::Resize { cols, rows } => {
218                    terminal.backend_mut().resize(cols, rows);
219                    let _ = terminal.resize(ratatui::layout::Rect::new(0, 0, cols, rows));
220                    let _ = terminal.clear();
221                    needs_redraw = true;
222                }
223                ProcessInput::Kill => return,
224            }
225        }
226
227        let tick_changed = app.tick(delta_ms);
228        if tick_changed {
229            needs_redraw = true;
230        }
231
232        if app.should_quit() {
233            break;
234        }
235    }
236
237    let _ = terminal.show_cursor();
238    let _ = terminal.flush();
239}