diff options
Diffstat (limited to 'src/blocking/input.rs')
-rw-r--r-- | src/blocking/input.rs | 51 |
1 files changed, 49 insertions, 2 deletions
diff --git a/src/blocking/input.rs b/src/blocking/input.rs index 6b466a2..bdc916b 100644 --- a/src/blocking/input.rs +++ b/src/blocking/input.rs @@ -1,6 +1,53 @@ use crate::error::*; use std::io::Read as _; +use std::os::unix::io::AsRawFd as _; + +pub struct RawGuard { + termios: nix::sys::termios::Termios, + cleaned_up: bool, +} + +impl RawGuard { + #[allow(clippy::new_without_default)] + pub fn new() -> Result<Self> { + let stdin = std::io::stdin().as_raw_fd(); + let termios = + nix::sys::termios::tcgetattr(stdin).map_err(Error::SetRaw)?; + let mut termios_raw = termios.clone(); + nix::sys::termios::cfmakeraw(&mut termios_raw); + nix::sys::termios::tcsetattr( + stdin, + nix::sys::termios::SetArg::TCSANOW, + &termios_raw, + ) + .map_err(Error::SetRaw)?; + Ok(Self { + termios, + cleaned_up: false, + }) + } + + pub fn cleanup(&mut self) -> Result<()> { + if self.cleaned_up { + return Ok(()); + } + self.cleaned_up = true; + let stdin = std::io::stdin().as_raw_fd(); + nix::sys::termios::tcsetattr( + stdin, + nix::sys::termios::SetArg::TCSANOW, + &self.termios, + ) + .map_err(Error::UnsetRaw) + } +} + +impl Drop for RawGuard { + fn drop(&mut self) { + let _ = self.cleanup(); + } +} pub struct Input { buf: Vec<u8>, @@ -15,8 +62,8 @@ pub struct Input { #[allow(clippy::new_without_default)] impl Input { - pub fn new() -> Result<(Self, crate::RawGuard)> { - Ok((Self::new_without_raw(), crate::RawGuard::new()?)) + pub fn new() -> Result<(Self, RawGuard)> { + Ok((Self::new_without_raw(), RawGuard::new()?)) } pub fn new_without_raw() -> Self { |