Skip to content

Instantly share code, notes, and snippets.

@Kijewski
Created January 21, 2025 22:26
Show Gist options
  • Save Kijewski/bbe708e7cdda1bac08a5568230f77e55 to your computer and use it in GitHub Desktop.
Save Kijewski/bbe708e7cdda1bac08a5568230f77e55 to your computer and use it in GitHub Desktop.
Wait for any key to be pressed
use rustix::{event, fd, io, stdio, termios};
pub fn pause() -> Result<(), io::Errno> {
let attrs = termios::tcgetattr(FD)?;
// clear any stray input from STDIN
let _ = termios::tcflush(FD, termios::QueueSelector::IFlush);
// set STDIN to trap ctrl+c, etc., disable line mode, don't echo input
let mut new_attrs = attrs.clone();
new_attrs.special_codes[termios::SpecialCodeIndex::VINTR] = 0;
new_attrs.special_codes[termios::SpecialCodeIndex::VQUIT] = 0;
new_attrs.special_codes[termios::SpecialCodeIndex::VKILL] = 0;
new_attrs.special_codes[termios::SpecialCodeIndex::VEOF] = 0;
new_attrs.local_modes -= termios::LocalModes::ECHO | termios::LocalModes::ICANON;
new_attrs.local_modes |= termios::LocalModes::ISIG | termios::LocalModes::NOFLSH;
termios::tcsetattr(FD, termios::OptionalActions::Now, &new_attrs)?;
let reset_terminal = ResetTerminal(&attrs);
// await input
let events = event::PollFlags::IN
| event::PollFlags::PRI
| event::PollFlags::RDBAND
| event::PollFlags::RDNORM
| event::PollFlags::RDHUP
| event::PollFlags::ERR
| event::PollFlags::HUP
| event::PollFlags::NVAL;
match event::poll(&mut [event::PollFd::new(&FD, events)], -1) {
Ok(_) | Err(io::Errno::WOULDBLOCK) | Err(io::Errno::INTR) => (),
Err(err) => return Err(err),
}
// reset changes to terminal
drop(reset_terminal);
// clear any input on STDIN
let _ = termios::tcflush(FD, termios::QueueSelector::IFlush);
Ok(())
}
const FD: fd::BorrowedFd<'static> = stdio::stdin();
struct ResetTerminal<'a>(&'a termios::Termios);
impl Drop for ResetTerminal<'_> {
#[inline]
fn drop(&mut self) {
let _ = termios::tcsetattr(FD, termios::OptionalActions::Now, self.0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment