hyprstream_core/tui/
process.rs1use std::io::{self, Write};
9
10use tokio::sync::mpsc;
11use waxterm::app::{TerminalApp, TerminalConfig};
12use waxterm::backend::AnsiBackend;
13use waxterm::input::InputParser;
14
15pub enum ProcessInput {
17 Stdin(Vec<u8>),
19 Resize { cols: u16, rows: u16 },
21 Kill,
23}
24
25pub struct PaneProcess {
31 pub stdout_rx: mpsc::Receiver<Vec<u8>>,
32 pub input_tx: mpsc::Sender<ProcessInput>,
33}
34
35struct 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#[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 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 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
128pub 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 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
166fn 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 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 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}