From c26d2f0a97ca63c530ace19d453ab3156e63fadc Mon Sep 17 00:00:00 2001 From: Matthias Devlamynck Date: Tue, 11 Jul 2017 10:05:36 +0200 Subject: [PATCH] Implement hide cursor wrapper type --- src/cursor.rs | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/cursor.rs b/src/cursor.rs index 5cfa72e..541507e 100644 --- a/src/cursor.rs +++ b/src/cursor.rs @@ -1,6 +1,7 @@ //! Cursor movement. use std::fmt; +use std::ops; use std::io::{self, Write, Error, ErrorKind, Read}; use async::async_stdin; use std::time::{SystemTime, Duration}; @@ -135,3 +136,48 @@ impl DetectCursorPos for W { Ok((cx, cy)) } } + +/// Hide the cursor for the lifetime of this struct. +/// It will hide the cursor on creation with from() and show it back on drop(). +pub struct HideCursor { + /// The output target. + output: W, +} + +impl HideCursor { + /// Create a hide cursor wrapper struct for the provided output and hides the cursor. + pub fn from(mut output: W) -> Self { + write!(output, "{}", Hide).expect("hide the cursor"); + HideCursor { output: output } + } +} + +impl Drop for HideCursor { + fn drop(&mut self) { + write!(self, "{}", Show).expect("show the cursor"); + } +} + +impl ops::Deref for HideCursor { + type Target = W; + + fn deref(&self) -> &W { + &self.output + } +} + +impl ops::DerefMut for HideCursor { + fn deref_mut(&mut self) -> &mut W { + &mut self.output + } +} + +impl Write for HideCursor { + fn write(&mut self, buf: &[u8]) -> io::Result { + self.output.write(buf) + } + + fn flush(&mut self) -> io::Result<()> { + self.output.flush() + } +}