Skip to content
187 changes: 138 additions & 49 deletions src/app.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
pub mod pacing;

use std::io::{self, Write};
use std::time::Duration;
use std::time::{Duration, Instant};

use crossterm::event::{Event, EventStream, KeyEventKind};
use futures::StreamExt;
use futures::{Stream, StreamExt};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::Rect;
use ratatui::Terminal;
Expand All @@ -13,6 +15,30 @@ use crate::pane::CompositePane;
use crate::ui::WorkspaceWidget;
use crate::wm::WindowManager;

pub use pacing::{FramePacer, LoopStats, ECHO_GRACE, FRAME_FLOOR};

/// Cadence of timers, RPC waiters and STT draining (PTY output no longer waits for it).
pub const TICK: Duration = Duration::from_millis(16);

/// The always-on foreground RPC socket: request stream plus its handler.
pub type LiveRpcPair = (crate::api::live::LiveRpcRx, crate::api::live::LiveRpcHandler);

/// Resolves on SIGINT (Ctrl+C), SIGTERM or SIGHUP.
async fn host_shutdown_signal() {
#[cfg(unix)]
let (mut sigterm, mut sighup) = {
use tokio::signal::unix::{signal, SignalKind};
(signal(SignalKind::terminate()).ok(), signal(SignalKind::hangup()).ok())
};
#[cfg(not(unix))]
let (mut sigterm, mut sighup) = ((), ());
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = next_unix_signal(&mut sigterm) => {}
_ = next_unix_signal(&mut sighup) => {}
}
}

static HOST_OUT_TAP: std::sync::OnceLock<crate::traffic::TrafficTap> = std::sync::OnceLock::new();

/// `io::Stdout` wrapper that counts every byte written to the host terminal (hook H29,
Expand Down Expand Up @@ -120,46 +146,84 @@ impl App {
) -> Result<()> {
self.wm.set_tui_cell_grid_mode(true);
let _ = terminal.hide_cursor();
let mut reader = EventStream::new();
let reader = EventStream::new();
let input_tap = self.wm.traffic_meter().open_channel(
crate::traffic::Origin::HostTty,
"host-input",
None,
crate::traffic::Role::Wire,
);
let (mut live_rx, mut live) = match crate::api::live::LiveRpc::start(self.wm.traffic_meter()) {
Some((rx, handler)) => (Some(rx), Some(handler)),
None => {
crate::pty::set_live_socket(None);
(None, None)
let live = crate::api::live::LiveRpc::start(self.wm.traffic_meter());
if live.is_none() {
crate::pty::set_live_socket(None);
}
let draw = |app: &mut App| -> Result<()> {
terminal.draw(|frame| {
let area = frame.area();
app.last_viewport = area;
let _ = app.wm.resize_all(area);
frame.render_widget(WorkspaceWidget::new(&app.wm), area);
crate::ui::gui_font::geometric::sanitize_tui_pua_buffer(
frame.buffer_mut(),
app.wm.config().glyphs,
);
})?;
Ok(())
};
let events = reader.inspect(|item| {
if item.is_ok() {
input_tap.event(1);
}
});
self.run_loop(events, draw, live, host_shutdown_signal(), &LoopStats::default()).await
}

/// The event loop proper, generic over the host so it can be driven headlessly: `events` is
/// the host input stream, `draw` paints one frame, `shutdown` resolves when the process is
/// asked to stop.
///
/// PTY output wakes the loop through [`crate::pty::wake`] and is drained at once; redraws
/// are paced by a [`FramePacer`]. The `select!` is `biased`, in an order chosen so that no
/// arm can starve another:
/// 1. the 16 ms tick (rate-limited by its timer, so it cannot starve anything);
/// 2. shutdown signals;
/// 3. host input, ahead of everything a flooding pane can keep ready;
/// 4. RPC requests;
/// 5. the frame deadline;
/// 6. PTY output, last: it may be ready on every turn during a flood, and each drain is
/// bounded (32 x 8 KiB per pane), so input is consumed at most two turns after it arrives.
pub async fn run_loop<S, D, Q>(
&mut self,
mut events: S,
mut draw: D,
live: Option<LiveRpcPair>,
shutdown: Q,
stats: &LoopStats,
) -> Result<()>
where
S: Stream<Item = io::Result<Event>> + Unpin,
D: FnMut(&mut App) -> Result<()>,
Q: std::future::Future<Output = ()>,
{
let (mut live_rx, mut live) = match live {
Some((rx, handler)) => (Some(rx), Some(handler)),
None => (None, None),
};
let mut tick = tokio::time::interval(Duration::from_millis(16));
let mut tick = tokio::time::interval(TICK);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut input_errors: u8 = 0;
let ctrl_c = tokio::signal::ctrl_c();
tokio::pin!(ctrl_c);
#[cfg(unix)]
let (mut sigterm, mut sighup) = {
use tokio::signal::unix::{signal, SignalKind};
(signal(SignalKind::terminate()).ok(), signal(SignalKind::hangup()).ok())
};
#[cfg(not(unix))]
let (mut sigterm, mut sighup) = ((), ());
let mut pacer = FramePacer::default();
let mut output_seen = crate::pty::wake::output_seq();
tokio::pin!(shutdown);

loop {
if self.needs_redraw {
terminal.draw(|frame| {
let area = frame.area();
self.last_viewport = area;
let _ = self.wm.resize_all(area);
frame.render_widget(WorkspaceWidget::new(&self.wm), area);
crate::ui::gui_font::geometric::sanitize_tui_pua_buffer(
frame.buffer_mut(),
self.wm.config().glyphs,
);
})?;
LoopStats::bump(&stats.turns);
let now = Instant::now();
if self.needs_redraw && pacer.can_draw(now) {
draw(self)?;
self.needs_redraw = false;
pacer.drew(now);
LoopStats::bump(&stats.draws);
}

self.flush_osc52_to_host()?;
Expand All @@ -168,36 +232,53 @@ impl App {
break;
}

let frame_due = tokio::time::Instant::from_std(pacer.due(now));
tokio::select! {
maybe_event = reader.next() => {
if matches!(maybe_event, Some(Ok(_))) {
input_tap.event(1);
biased;
_ = tick.tick() => {
LoopStats::bump(&stats.ticks);
if let Some(handler) = live.as_mut() {
handler.poll_waiters(&mut self.wm);
}
self.wm.drain_stt_events();
if self.poll_all_ptys() {
pacer.output_arrived();
}
}
_ = &mut shutdown => {
self.should_quit = true;
}
maybe_event = events.next() => {
let redraw_was_pending = self.needs_redraw;
let sent_before = crate::pty::wake::input_seq();
self.on_input_stream_item(maybe_event, &mut input_errors);
if crate::pty::wake::input_seq() != sent_before {
pacer.input_sent_to_pty(Instant::now(), redraw_was_pending);
}
LoopStats::bump(&stats.inputs);
stats.last_input_turn.set(stats.turns.get());
}
Some((line, reply)) = next_live_request(&mut live_rx) => {
if let Some(handler) = live.as_mut() {
handler.handle(&mut self.wm, &line, reply);
}
self.needs_redraw = true;
}
_ = tick.tick() => {
if let Some(handler) = live.as_mut() {
handler.poll_waiters(&mut self.wm);
_ = tokio::time::sleep_until(frame_due), if self.needs_redraw => {}
_ = crate::pty::wake::output_ready(&mut output_seen) => {
LoopStats::bump(&stats.pty_wakes);
let drained = self.wm.drain_pty_output();
if drained.exited {
// Reap or hold the pane now, exactly as the tick would.
self.poll_all_ptys();
}
self.wm.drain_stt_events();
if self.poll_all_ptys() {
if drained.changed || drained.exited {
self.needs_redraw = true;
pacer.output_arrived();
}
}
_ = &mut ctrl_c => {
self.should_quit = true;
}
_ = next_unix_signal(&mut sigterm) => {
self.should_quit = true;
}
_ = next_unix_signal(&mut sighup) => {
self.should_quit = true;
// Let the runtime turn its timer and I/O drivers even if output keeps this
// arm ready on every turn (matters on a current-thread runtime).
tokio::task::yield_now().await;
}
}
}
Expand Down Expand Up @@ -246,9 +327,7 @@ impl App {
match item {
Some(Ok(event)) => {
*consecutive_errors = 0;
if let Err(err) = self.handle_crossterm_event(event) {
self.report_event_error(&err);
}
let _ = self.handle_crossterm_event(event);
self.needs_redraw = true;
}
Some(Err(_)) => {
Expand All @@ -267,7 +346,17 @@ impl App {
self.needs_redraw = true;
}

/// Handles one host event. Always `Ok`: an error from handling it (a refused or failed PTY
/// write on one pane, a rejected command) is shown in the status line and must never end
/// the event loop of any front end (the GUI loops propagate this result with `?`).
pub fn handle_crossterm_event(&mut self, event: Event) -> Result<()> {
if let Err(err) = self.dispatch_crossterm_event(event) {
self.report_event_error(&err);
}
Ok(())
}

fn dispatch_crossterm_event(&mut self, event: Event) -> Result<()> {
match event {
Event::Key(key) if matches!(key.kind, KeyEventKind::Press | KeyEventKind::Repeat) => {
if handle_wm_key_event(&mut self.wm, key)? == AppAction::Quit {
Expand Down
Loading
Loading