Skip to main content

waxterm/
runtime.rs

1use std::io::{self, BufWriter, Write};
2
3use ratatui::Terminal;
4
5use crate::app::{TerminalApp, TerminalConfig};
6use crate::backend::AnsiBackend;
7use crate::input::InputParser;
8#[cfg(target_os = "wasi")]
9use crate::input::StdinPoller;
10
11/// Synchronous event loop. Works on both native and WASI.
12pub fn run_sync<A: TerminalApp>(mut app: A, config: TerminalConfig) -> io::Result<()> {
13    let stdout = io::stdout();
14    let backend = AnsiBackend::new(
15        BufWriter::with_capacity(config.buf_capacity, stdout.lock()),
16        config.cols,
17        config.rows,
18        config.heartbeat,
19    );
20    let mut terminal = Terminal::new(backend)?;
21
22    // Build input parser with app-provided OSC extensions
23    let parser = InputParser::new(app.input_extensions());
24
25    // Hide cursor + clear screen (no alternate screen — simpler for Wanix)
26    let mut out = io::stdout();
27    write!(out, "\x1b[?25l\x1b[2J\x1b[H")?;
28    out.flush()?;
29
30    #[cfg(not(target_os = "wasi"))]
31    {
32        run_native(&mut app, &mut terminal, &parser, &config)?;
33    }
34
35    #[cfg(target_os = "wasi")]
36    {
37        run_wasi(&mut app, &mut terminal, &parser, &config)?;
38    }
39
40    // Restore terminal
41    let mut out = io::stdout();
42    write!(out, "\x1b[?25h\x1b[?1049l")?;
43    out.flush()?;
44
45    Ok(())
46}
47
48/// Async wrapper: runs sync loop on blocking thread. Native only.
49#[cfg(feature = "tokio")]
50pub async fn run_async<A: TerminalApp + Send + 'static>(
51    app: A,
52    config: TerminalConfig,
53) -> io::Result<()> {
54    tokio::task::spawn_blocking(move || run_sync(app, config))
55        .await
56        .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
57}
58
59// --- Native event loop ---
60
61#[cfg(not(target_os = "wasi"))]
62fn run_native<A, W>(
63    app: &mut A,
64    terminal: &mut Terminal<AnsiBackend<W>>,
65    parser: &InputParser<A::Command>,
66    config: &TerminalConfig,
67) -> io::Result<()>
68where
69    A: TerminalApp,
70    W: Write,
71{
72    use std::time::{Duration, Instant};
73
74    let original_termios = enable_raw_mode()?;
75    let mut stdin = io::stdin();
76    let mut buf = [0u8; 256];
77    let mut needs_redraw = true;
78    let mut last_tick = Instant::now();
79    let frame_ms = 1000 / u64::from(config.fps);
80
81    loop {
82        if needs_redraw {
83            terminal.draw(|frame| app.render(frame))?;
84            needs_redraw = false;
85        }
86
87        std::thread::sleep(Duration::from_millis(frame_ms));
88
89        let now = Instant::now();
90        let delta_ms = now.duration_since(last_tick).as_millis() as u64;
91        last_tick = now;
92
93        // Non-blocking stdin read
94        use std::io::Read;
95        match stdin.read(&mut buf) {
96            Ok(n) if n > 0 => {
97                let cmds = parser.parse(&buf[..n]);
98                for cmd in cmds {
99                    if app.handle_input(cmd) {
100                        needs_redraw = true;
101                    }
102                }
103            }
104            _ => {}
105        }
106
107        if app.tick(delta_ms) {
108            needs_redraw = true;
109        }
110
111        if app.should_quit() {
112            break;
113        }
114    }
115
116    disable_raw_mode(original_termios);
117    Ok(())
118}
119
120#[cfg(not(target_os = "wasi"))]
121fn enable_raw_mode() -> io::Result<libc::termios> {
122    unsafe {
123        let mut original = std::mem::zeroed::<libc::termios>();
124        if libc::tcgetattr(0, &mut original) != 0 {
125            return Err(io::Error::last_os_error());
126        }
127        let mut raw = original;
128        raw.c_lflag &= !(libc::ECHO | libc::ICANON);
129        raw.c_iflag &= !libc::ICRNL; // CR → NL translation off; Enter delivers 0x0D
130        raw.c_cc[libc::VMIN] = 0;
131        raw.c_cc[libc::VTIME] = 0;
132        if libc::tcsetattr(0, libc::TCSANOW, &raw) != 0 {
133            return Err(io::Error::last_os_error());
134        }
135        Ok(original)
136    }
137}
138
139#[cfg(not(target_os = "wasi"))]
140fn disable_raw_mode(original: libc::termios) {
141    unsafe {
142        libc::tcsetattr(0, libc::TCSANOW, &original);
143    }
144}
145
146// --- WASI event loop ---
147
148#[cfg(target_os = "wasi")]
149fn run_wasi<A, W>(
150    app: &mut A,
151    terminal: &mut Terminal<AnsiBackend<W>>,
152    parser: &InputParser<A::Command>,
153    config: &TerminalConfig,
154) -> io::Result<()>
155where
156    A: TerminalApp,
157    W: Write,
158{
159    use std::time::{Duration, Instant};
160
161    let mut poller = StdinPoller::new();
162    let frame_ms = (1000 / u64::from(config.fps)) as u64;
163    let mut render_timer_ms: u64 = frame_ms; // draw immediately on first tick
164    let mut force_redraw = false;
165    let mut last_tick = Instant::now();
166
167    loop {
168        // Render at target fps, or immediately when input changes state
169        if render_timer_ms >= frame_ms || force_redraw {
170            terminal.draw(|frame| app.render(frame))?;
171            render_timer_ms = 0;
172            force_redraw = false;
173        }
174
175        // Short sleep so the JS reader can drain stdout between frames.
176        std::thread::sleep(Duration::from_millis(5));
177
178        // Clamped delta: fallback to 5ms if clock_time_get is unimplemented,
179        // cap at 50ms to prevent catch-up after focus loss.
180        let now = Instant::now();
181        let delta_ms = now.duration_since(last_tick).as_millis().clamp(5, 50) as u64;
182        last_tick = now;
183
184        // Poll stdin (non-blocking)
185        let data = poller.read();
186        if !data.is_empty() {
187            let cmds = parser.parse(data);
188            for cmd in cmds {
189                app.handle_input(cmd);
190            }
191            force_redraw = true;
192        }
193
194        // Advance app state (decoupled from render rate)
195        if app.tick(delta_ms) {
196            // tick may produce output worth rendering
197        }
198        render_timer_ms += delta_ms;
199
200        if app.should_quit() {
201            break;
202        }
203    }
204
205    Ok(())
206}