Async event loops
Most apps can read input synchronously with
Program::read_event,
Program::try_read_event,
or
Program::poll_event.
Program owns the terminal session, input source, and modes. Draw through the
pure renderer it contains with program.screen_mut().
With the async feature,
Program::event_stream
gives you a futures_core::Stream of io::Result<Event> over the program’s own
decoder. The stream is owned, not borrowed, so the same async task can read
input, resize, and render in one tokio::select!. The feature is
runtime-agnostic: it depends on futures-core, not tokio. If you need the
shared input source directly,
Program::event_source
returns the Arc<Mutex<EventSource<I>>>.
Enable the feature in Cargo.toml:
[dependencies]
uncurses = { git = "https://github.com/aymanbagabas/uncurses", features = ["async"] }The Program::event_stream() path
This is the recommended path for async apps. It mirrors examples/examples/async_screen.rs:
terminal input and a frame timer share one select!, and the same task renders.
use std::time::Duration;
use tokio_stream::StreamExt;
use uncurses::buffer::{Bounded, SurfaceMut};
use uncurses::event::{Event, Key};
use uncurses::program::Program;
use uncurses::screen::Screen;
use uncurses::style::Style;
use uncurses::terminal::{Stdin, Stdout};
use uncurses::text::TextSurface;
const FRAME: Duration = Duration::from_millis(16);
#[tokio::main]
async fn main() -> std::io::Result<()> {
let mut program = Program::stdio()?;
program.init()?;
program.enter_alt_screen()?;
program.hide_cursor()?;
let result = run(&mut program).await;
let finish = program.finish();
result.and(finish)
}
async fn run(program: &mut Program<Stdin, Stdout>) -> std::io::Result<()> {
let quit_keys: [Key; 3] = ["q", "esc", "ctrl+c"].map(|s| s.parse().unwrap());
let mut events = program.event_stream();
let mut ticker = tokio::time::interval(FRAME);
let mut frames = 0u64;
loop {
tokio::select! {
maybe = events.next() => {
let Some(ev) = maybe else { break };
let ev = ev?;
match ev {
Event::KeyPress(ref key) if quit_keys.contains(key) => break,
Event::Resize(_) => program.autoresize()?,
_ => {}
}
}
_ = ticker.tick() => {
frames += 1;
draw(program.screen_mut(), frames)?;
}
}
}
Ok(())
}
fn draw(screen: &mut Screen<Stdout>, frames: u64) -> std::io::Result<()> {
screen.clear();
let w = screen.width();
screen.set_str(
(0, 0),
&format!("async uncurses frame {frames}, width {w}"),
Style::default(),
);
screen.render()
}The full game version is examples/examples/async_arcade.rs. It uses the same
shape, then adds async game tasks feeding messages into the render loop.
Capability queries in an async loop
Capability replies are ordinary events. Write selected queries before the loop and flush once. Use an async deadline for startup. The application detects DA1 and keeps keys for its normal loop. This current-source function uses Tokio’s timeout:
use std::io::Write;
use std::time::Duration;
use tokio_stream::StreamExt;
use uncurses::event::Event;
use uncurses::program::{Probe, Program};
use uncurses::terminal::{Stdin, Stdout};
async fn run(program: &mut Program<Stdin, Stdout>) -> std::io::Result<()> {
let mut probe = Probe::new(program.env());
probe.terminal_name = true;
let mut caps = probe.query_capabilities(program.screen_mut(), true)?;
program.screen_mut().flush()?;
let mut events = program.event_stream();
let deadline = tokio::time::Instant::now() + Duration::from_millis(300);
let mut keys = Vec::new();
while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.next()).await {
let event = event?;
caps.record(&event);
match event {
Event::PrimaryDeviceAttributes(_) => break,
Event::KeyPress(_) | Event::KeyRelease(_) => keys.push(event),
_ => {}
}
}
for event in keys.into_iter().rev() {
program.unread_event(event);
}
program.apply_defaults(&caps)?;
Ok(())
}This sample selects terminal-name discovery.
Handle resize, paste, and other application events in the collection loop, or retain them for later.
For cursor measurements, route replies according to selected query order and
account for row-1 F3 ambiguity.
See Querying the terminal for those requirements.
A timeout leaves requests active. Keep identified late replies recordable.
The async_screen.rs example combines discovery with a frame timer.
Worker requests and wakes
For a synchronous reader, obtain a
Waker from the shared event source.
Set your request flag before calling wake().
Check that flag after each read result, including successful input and resize events.
A ready or queued event takes priority and leaves the wake pending.
When a later read finds no event, it clears the wake and returns Interrupted.
The corresponding poll() returns false.
Concurrent wakes may coalesce. Keep the requested work in a shared flag or queue.
See the wake example
for a complete synchronous loop.
For an async reader, use a channel or cancellation future beside events.next() in select!.
A source wake makes the stream retry; the stream yields terminal events and errors.
See Waker::wake for the exact contract.
Cleaning up
You do not need to drop Program::event_stream() before
Program::finish,
Program::pause, or
Program::resume. The
stream shares the input source by handle and can stay live across those calls.
Ratatui backend async input
With uncurses-ratatui’s async feature, the backend has the same shared async
read path. Use
UncursesBackend::event_stream
inside the same select! loop that draws your Ratatui frames.
Low-level EventSource::into_stream()
Use this only when you are not using Program. It is the by-hand path: put the
terminal in raw mode yourself, build an EventSource
over the input half, and turn it into an EventStream.
use tokio_stream::StreamExt;
use uncurses::event::{Event, EventSource, Key};
use uncurses::terminal::Terminal;
async fn run() -> std::io::Result<()> {
let mut term = Terminal::stdio();
term.make_raw()?;
let result = async {
let quit: Key = "ctrl+c".parse().unwrap();
#[cfg_attr(not(windows), allow(unused_mut))]
let mut source = EventSource::new(term.input())?;
let mut events = source.into_stream();
while let Some(event) = events.next().await {
match event? {
Event::KeyPress(ref k) if *k == quit => break,
_ => {}
}
// React and repaint through your own output half.
}
Ok(())
}
.await;
let restore = term.restore();
result.and(restore)
}