Refactor event loop from timer-driven to render-after-input

Replace the dual-rate timer rendering architecture with a direct
render-after-input loop. The old design used a background tokio task
(EventHandler) that ran two interval timers — 30 FPS while "active"
and 2 FPS when idle — forwarding events through an mpsc channel. This
introduced up to ~33ms of latency between a keypress and its screen
update, and added unnecessary complexity (background task, channel,
activity threshold heuristic).

The new design uses a single tokio::select! loop with three arms:
  1. Keyboard input: renders immediately after processing, then drains
     any additional buffered input via non-blocking poll before drawing
  2. Async command results: handles actions from the command channel
     (file I/O completion, etc.) and renders
  3. Idle timeout (500ms): renders for background updates like cursor
     blink

Structural changes:
- Remove Event enum, EventHandler struct, and its background task
- TerminalUI now owns crossterm::event::EventStream and the command
  output UnboundedReceiver directly
- EditorCore::new() returns (Self, UnboundedReceiver<EditorAction>)
  instead of storing the receiver internally
- Remove EditorCore::process_commands() — its logic moves into the
  main loop's select arm for command output
- Make EditorCore::handle_action() pub(crate) so the main loop can
  call it directly for command results
- Extract process_key() helper for KeyCode-to-Input mapping
- Add try_poll_crossterm() for non-blocking input draining

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Greg ShuflinandClaude Opus 4.6 committed 2026-02-09 11:05:00 -08:00
1 parent 8c04b1ee90
commit f80cc2da0d
2 files changed
+71 -118

No files matched your search

+3 -16
View File
@@ -60,12 +60,11 @@ pub(crate) struct EditorCore {
mode: Mode,
configuration: Configuration,
commands: Commands,
command_output_rx: UnboundedReceiver<EditorAction>,
pub(crate) should_quit: bool,
}
impl EditorCore {
pub(crate) fn new() -> Self {
pub(crate) fn new() -> (Self, UnboundedReceiver<EditorAction>) {
let mut buffers = HashMap::new();
let active_buffer = BufferId(0);
buffers.insert(active_buffer, Buffer::Text(TextBuffer::new()));
@@ -81,10 +80,9 @@ impl EditorCore {
configuration: Configuration::new(),
mode: Mode::Normal,
commands: Commands::new(command_tx),
command_output_rx,
should_quit: false,
};
core
(core, command_output_rx)
}
pub(crate) fn mode(&self) -> Mode {
self.mode
@@ -143,21 +141,10 @@ impl EditorCore {
}
}
pub(crate) fn process_commands(&mut self) {
if let Ok(action) = self.command_output_rx.try_recv() {
info!(?action, "Handling action from command output");
self.handle_action(action);
//TODO this should probably be handled by the command API itself, since this will break
//when teh command api starts emitting a vec of length greater than 1
self.handle_action(EditorAction::TransitionToMode(Mode::Normal));
}
}
/// `handle_action` is a very large method that is the entry point for the action handling
/// system.
#[tracing::instrument(skip(self))]
fn handle_action(&mut self, action: EditorAction) {
pub(crate) fn handle_action(&mut self, action: EditorAction) {
use EditorAction::*;
let mode = self.mode;
+68 -102
View File
@@ -6,107 +6,38 @@ use crossterm::{
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use futures::{FutureExt, StreamExt};
use futures::StreamExt;
use ratatui::prelude::{CrosstermBackend, Terminal};
use std::{
io::{self, stdout, Stdout},
time::Duration,
};
use tokio::{task::JoinHandle, time::Instant};
use tokio::sync::mpsc::UnboundedReceiver;
use tracing::info;
use crate::core::{EditorCore, Input};
use crate::core::{
actions::EditorAction, actions::EditorAction::TransitionToMode, EditorCore, Input, Mode,
};
use self::render::TerminalState;
enum Event {
Key(crossterm::event::KeyEvent),
Render,
}
struct EventHandler {
rx: tokio::sync::mpsc::UnboundedReceiver<Event>,
#[allow(dead_code)]
task: JoinHandle<()>,
}
impl EventHandler {
fn new() -> Self {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
let threshold_duration = Duration::from_secs_f64(0.5);
let fast_fps = 30;
let slow_fps = 2;
let mut fast_render_interval =
tokio::time::interval(Duration::from_secs_f64(1.0 / fast_fps as f64));
let mut slow_render_interval =
tokio::time::interval(Duration::from_secs_f64(1.0 / slow_fps as f64));
//TODO missed tick behavior
let mut crossterm_events = crossterm::event::EventStream::new();
let task = tokio::spawn(async move {
let mut last_terminal_event = Instant::now();
loop {
let render_delay = slow_render_interval.tick();
let fast_render_delay = fast_render_interval.tick();
let crossterm_event = crossterm_events.next().fuse();
tokio::select! {
maybe_event = crossterm_event => {
last_terminal_event = Instant::now();
match maybe_event {
Some(Ok(event)) => match event {
CrosstermEvent::Key(key) if key.kind == event::KeyEventKind::Press => {
tx.send(Event::Key(key)).unwrap()
}
_ => ()
}
Some(Err(e)) => {
panic!("ERR: {}", e);
}
None => (),
}
},
_ = fast_render_delay => {
if last_terminal_event.elapsed() < threshold_duration {
tx.send(Event::Render).unwrap();
}
}
_ = render_delay => {
tx.send(Event::Render).unwrap();
}
}
}
});
EventHandler { rx, task }
}
async fn next(&mut self) -> Result<Event> {
self.rx
.recv()
.await
.ok_or(color_eyre::eyre::eyre!("Unable to get event"))
}
}
struct TerminalUI {
terminal: Terminal<CrosstermBackend<Stdout>>,
terminal_state: TerminalState,
event_handler: EventHandler,
crossterm_events: crossterm::event::EventStream,
command_output_rx: UnboundedReceiver<EditorAction>,
editor_core: EditorCore,
}
impl TerminalUI {
fn new() -> Self {
let terminal = Terminal::new(CrosstermBackend::new(stdout())).unwrap();
//TODO do soemthing with _commadn_rx
let editor_core = EditorCore::new();
let (editor_core, command_output_rx) = EditorCore::new();
Self {
terminal,
event_handler: EventHandler::new(),
crossterm_events: crossterm::event::EventStream::new(),
command_output_rx,
terminal_state: TerminalState::new(),
editor_core,
}
@@ -127,38 +58,73 @@ impl TerminalUI {
Ok(())
}
fn process_key(&mut self, key: crossterm::event::KeyEvent) {
let input = match key.code {
KeyCode::Char(ch) => Input::Character(ch),
KeyCode::Enter => Input::Newline,
KeyCode::Backspace => Input::Backspace,
KeyCode::Esc => Input::Escape,
KeyCode::Tab => Input::Tab,
_ => Input::None,
};
self.editor_core.send_input(input);
}
/// Non-blocking poll: returns the next crossterm event if one is immediately available.
fn try_poll_crossterm(&mut self) -> Option<CrosstermEvent> {
if crossterm::event::poll(Duration::ZERO).ok()? {
crossterm::event::read().ok()
} else {
None
}
}
/// The main loop of the TUI editor
async fn run(&mut self) -> Result<()> {
info!("Starting to run tui");
'outer: loop {
let evt = self.event_handler.next().await.unwrap();
match evt {
Event::Render => {
// Process any pending commands
self.editor_core.process_commands();
let idle_timeout = Duration::from_millis(500);
// Render the current state
self.terminal.draw(|mut frame| {
self.terminal_state
.render(&mut frame, &mut self.editor_core)
})?;
loop {
let mut needs_render = false;
if self.editor_core.should_quit {
break 'outer;
tokio::select! {
maybe_event = self.crossterm_events.next() => {
if let Some(Ok(CrosstermEvent::Key(key))) = maybe_event {
if key.kind == event::KeyEventKind::Press {
self.process_key(key);
needs_render = true;
}
}
// Drain any additional buffered input
while let Some(ct_event) = self.try_poll_crossterm() {
if let CrosstermEvent::Key(key) = ct_event {
if key.kind == event::KeyEventKind::Press {
self.process_key(key);
}
}
}
}
Event::Key(key) => {
let action = match key.code {
KeyCode::Char(ch) => Input::Character(ch),
KeyCode::Enter => Input::Newline,
KeyCode::Backspace => Input::Backspace,
KeyCode::Esc => Input::Escape,
KeyCode::Tab => Input::Tab,
_ => Input::None,
};
self.editor_core.send_input(action);
Some(action) = self.command_output_rx.recv() => {
info!(?action, "Handling action from command output");
self.editor_core.handle_action(action);
self.editor_core.handle_action(TransitionToMode(Mode::Normal));
needs_render = true;
}
_ = tokio::time::sleep(idle_timeout) => {
needs_render = true;
}
}
if needs_render {
self.terminal.draw(|mut frame| {
self.terminal_state
.render(&mut frame, &mut self.editor_core)
})?;
}
if self.editor_core.should_quit {
break;
}
}