Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

io::Result cleanup #232

Merged
merged 8 commits into from
Sep 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crossterm_cursor/src/sys/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,14 @@ pub fn show_cursor(show_cursor: bool) -> Result<()> {
Ok(())
}

pub fn pos() -> io::Result<(u16, u16)> {
pub fn pos() -> Result<(u16, u16)> {
unix::into_raw_mode()?;
let pos = pos_raw();
unix::disable_raw_mode()?;
pos
}

pub fn pos_raw() -> io::Result<(u16, u16)> {
pub fn pos_raw() -> Result<(u16, u16)> {
// Where is the cursor?
// Use `ESC [ 6 n`.
let mut stdout = io::stdout();
Expand Down
25 changes: 13 additions & 12 deletions crossterm_cursor/src/sys/winapi.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
//! This module handles some logic for cursor interaction in the windows console.

use std::io::{self, Result};
use std::io;

use winapi::{
shared::minwindef::{FALSE, TRUE},
um::wincon::{SetConsoleCursorInfo, SetConsoleCursorPosition, CONSOLE_CURSOR_INFO, COORD},
um::winnt::HANDLE,
};

use crossterm_utils::Result;
pub use crossterm_winapi::{is_true, Coord, Handle, HandleType, ScreenBuffer};

#[cfg(windows)]
Expand All @@ -32,7 +33,7 @@ pub struct Cursor {
}

impl Cursor {
pub fn new() -> io::Result<Cursor> {
pub fn new() -> Result<Cursor> {
Ok(Cursor {
screen_buffer: ScreenBuffer::from(Handle::new(HandleType::CurrentOutputHandle)?),
})
Expand All @@ -44,25 +45,25 @@ impl Cursor {
}

/// Set the cursor position to the given x and y. Note that this is 0 based.
pub fn goto(&self, x: i16, y: i16) -> io::Result<()> {
pub fn goto(&self, x: i16, y: i16) -> Result<()> {
if x < 0 || x >= <i16>::max_value() {
return Err(io::Error::new(
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Argument Out of Range Exception when setting cursor position to X: {}",
x
),
));
))?;
}

if y < 0 || y >= <i16>::max_value() {
return Err(io::Error::new(
Err(io::Error::new(
io::ErrorKind::Other,
format!(
"Argument Out of Range Exception when setting cursor position to Y: {}",
y
),
));
))?;
}

let position = COORD { X: x, Y: y };
Expand All @@ -72,14 +73,14 @@ impl Cursor {
**self.screen_buffer.get_handle(),
position,
)) {
return Err(io::Error::last_os_error());
Err(io::Error::last_os_error())?;
}
}
Ok(())
}

/// change the cursor visibility.
pub fn set_visibility(&self, visable: bool) -> io::Result<()> {
pub fn set_visibility(&self, visable: bool) -> Result<()> {
let cursor_info = CONSOLE_CURSOR_INFO {
dwSize: 100,
bVisible: if visable { TRUE } else { FALSE },
Expand All @@ -90,14 +91,14 @@ impl Cursor {
**self.screen_buffer.get_handle(),
&cursor_info,
)) {
return Err(io::Error::last_os_error());
Err(io::Error::last_os_error())?;
}
}
Ok(())
}

/// Reset to saved cursor position
pub fn reset_to_saved_position() -> io::Result<()> {
pub fn reset_to_saved_position() -> Result<()> {
let cursor = Cursor::new()?;

unsafe {
Expand All @@ -108,7 +109,7 @@ impl Cursor {
}

/// Save current cursor position to recall later.
pub fn save_cursor_pos() -> io::Result<()> {
pub fn save_cursor_pos() -> Result<()> {
let cursor = Cursor::new()?;
let position = cursor.position()?;

Expand Down
4 changes: 1 addition & 3 deletions crossterm_input/src/input.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
//! A module that contains all the actions related to reading input from the terminal.
//! Like reading a line, reading a character and reading asynchronously.

use std::io;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -31,7 +29,7 @@ mod windows_input;
/// Unix is using the 'TTY' and windows is using 'libc' C functions to read the input.
trait ITerminalInput {
/// Read one character from the user input
fn read_char(&self) -> io::Result<char>;
fn read_char(&self) -> Result<char>;
/// Read the input asynchronously from the user.
fn read_async(&self) -> AsyncReader;
/// Read the input asynchronously until a certain character is hit.
Expand Down
4 changes: 2 additions & 2 deletions crossterm_input/src/input/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ impl TerminalInput {
/// Err(e) => println!("error: {}", e),
/// }
/// ```
pub fn read_line(&self) -> io::Result<String> {
pub fn read_line(&self) -> Result<String> {
let mut rv = String::new();
io::stdin().read_line(&mut rv)?;
let len = rv.trim_end_matches(&['\r', '\n'][..]).len();
Expand All @@ -74,7 +74,7 @@ impl TerminalInput {
/// Err(e) => println!("error: {}", e),
/// }
/// ```
pub fn read_char(&self) -> io::Result<char> {
pub fn read_char(&self) -> Result<char> {
self.input.read_char()
}

Expand Down
2 changes: 1 addition & 1 deletion crossterm_input/src/input/unix_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ impl UnixInput {
}

impl ITerminalInput for UnixInput {
fn read_char(&self) -> io::Result<char> {
fn read_char(&self) -> Result<char> {
read_char_raw()
}

Expand Down
20 changes: 8 additions & 12 deletions crossterm_input/src/input/windows_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,27 +42,23 @@ const ENABLE_MOUSE_MODE: u32 = 0x0010 | 0x0080 | 0x0008;
static mut ORIG_MODE: u32 = 0;

impl ITerminalInput for WindowsInput {
fn read_char(&self) -> io::Result<char> {
fn read_char(&self) -> Result<char> {
// _getwch is without echo and _getwche is with echo
let pressed_char = unsafe { _getwche() };

// we could return error but maybe option to keep listening until valid character is inputted.
if pressed_char == 0 || pressed_char == 0xe0 {
return Err(io::Error::new(
Err(io::Error::new(
io::ErrorKind::Other,
"Given input char is not a valid char, mostly occurs when pressing special keys",
));
))?;
}

match char::from_u32(pressed_char as u32) {
Some(c) => {
return Ok(c);
}
None => Err(io::Error::new(
io::ErrorKind::Other,
"Could not parse given input to char",
)),
}
let ch = char::from_u32(pressed_char as u32).ok_or_else(|| {
io::Error::new(io::ErrorKind::Other, "Could not parse given input to char")
})?;

Ok(ch)
}

fn read_async(&self) -> AsyncReader {
Expand Down
18 changes: 11 additions & 7 deletions crossterm_input/src/sys/unix.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
use std::os::unix::io::AsRawFd;
use std::{fs, io};

use crossterm_utils::Result;

/// Get the TTY device.
///
/// This allows for getting stdio representing _only_ the TTY, and not other streams.
pub fn get_tty() -> io::Result<fs::File> {
fs::OpenOptions::new()
pub fn get_tty() -> Result<fs::File> {
let file = fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")
.open("/dev/tty")?;

Ok(file)
}

fn get_tty_fd() -> io::Result<i32> {
fn get_tty_fd() -> Result<i32> {
let fd = unsafe {
if libc::isatty(libc::STDIN_FILENO) == 1 {
libc::STDIN_FILENO
Expand All @@ -23,7 +27,7 @@ fn get_tty_fd() -> io::Result<i32> {
Ok(fd)
}

pub fn read_char_raw() -> io::Result<char> {
pub fn read_char_raw() -> Result<char> {
let mut buf = [0u8; 20];

let fd = get_tty_fd()?;
Expand All @@ -50,7 +54,7 @@ pub fn read_char_raw() -> io::Result<char> {

pressed_char
}
};
}?;

rv
Ok(rv)
}
10 changes: 4 additions & 6 deletions crossterm_screen/src/screen/alternate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,9 @@
//! For an example of this behavior, consider when vim is launched from bash.
//! Vim uses the entirety of the screen to edit the file, then returning to bash leaves the original buffer unchanged.

use std::io;

#[cfg(windows)]
use crossterm_utils::supports_ansi;
use crossterm_utils::Result;

#[cfg(windows)]
use crate::sys::winapi::ToAlternateScreenCommand;
Expand Down Expand Up @@ -38,7 +37,7 @@ impl AlternateScreen {
/// The alternate buffer dimensions are exactly the same as the window, without any scrollback region.
/// For an example of this behavior, consider when vim is launched from bash.
/// Vim uses the entirety of the screen to edit the file, then returning to bash leaves the original buffer unchanged.
pub fn to_alternate(raw_mode: bool) -> io::Result<AlternateScreen> {
pub fn to_alternate(raw_mode: bool) -> Result<AlternateScreen> {
#[cfg(windows)]
let command = if supports_ansi() {
Box::from(sys::ToAlternateScreenCommand::new())
Expand Down Expand Up @@ -68,9 +67,8 @@ impl AlternateScreen {
}

/// Switch the alternate screen back to the main screen.
pub fn to_main(&self) -> io::Result<()> {
self.command.disable()?;
Ok(())
pub fn to_main(&self) -> Result<()> {
self.command.disable()
}
}

Expand Down
12 changes: 7 additions & 5 deletions crossterm_screen/src/screen/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
//!
//! With these modes you can easier design the terminal screen.

use std::io::{self, Stdout, Write};
use std::io::{Stdout, Write};

use crossterm_utils::Result;

use crate::sys;

Expand All @@ -27,7 +29,7 @@ pub struct RawScreen {

impl RawScreen {
/// Put terminal in raw mode.
pub fn into_raw_mode() -> io::Result<RawScreen> {
pub fn into_raw_mode() -> Result<RawScreen> {
#[cfg(unix)]
let mut command = sys::unix::RawModeCommand::new();
#[cfg(windows)]
Expand All @@ -39,7 +41,7 @@ impl RawScreen {
}

/// Put terminal back in original modes.
pub fn disable_raw_mode() -> io::Result<()> {
pub fn disable_raw_mode() -> Result<()> {
#[cfg(unix)]
let mut command = sys::unix::RawModeCommand::new();
#[cfg(windows)]
Expand Down Expand Up @@ -67,11 +69,11 @@ pub trait IntoRawMode: Write + Sized {
/// Raw mode means that stdin won't be printed (it will instead have to be written manually by
/// the program). Furthermore, the input isn't canonicalised or buffered (that is, you can
/// read from stdin one byte of a time). The output is neither modified in any way.
fn into_raw_mode(self) -> io::Result<RawScreen>;
fn into_raw_mode(self) -> Result<RawScreen>;
}

impl IntoRawMode for Stdout {
fn into_raw_mode(self) -> io::Result<RawScreen> {
fn into_raw_mode(self) -> Result<RawScreen> {
RawScreen::into_raw_mode()?;
// this make's sure that raw screen will be disabled when it goes out of scope.
Ok(RawScreen { drop: true })
Expand Down
2 changes: 1 addition & 1 deletion crossterm_screen/src/sys/unix.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::io::Result;
use crossterm_utils::Result;

/// This command is used for enabling and disabling raw mode for the terminal.
pub struct RawModeCommand;
Expand Down
6 changes: 2 additions & 4 deletions crossterm_screen/src/sys/winapi.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::io;

use winapi::shared::minwindef::DWORD;
use winapi::um::wincon;

Expand Down Expand Up @@ -27,7 +25,7 @@ impl RawModeCommand {

impl RawModeCommand {
/// Enables raw mode.
pub fn enable(&mut self) -> io::Result<()> {
pub fn enable(&mut self) -> Result<()> {
let console_mode = ConsoleMode::new()?;

let dw_mode = console_mode.mode()?;
Expand All @@ -40,7 +38,7 @@ impl RawModeCommand {
}

/// Disables raw mode.
pub fn disable(&self) -> io::Result<()> {
pub fn disable(&self) -> Result<()> {
let console_mode = ConsoleMode::new()?;

let dw_mode = console_mode.mode()?;
Expand Down
3 changes: 1 addition & 2 deletions crossterm_style/src/color.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

use std::clone::Clone;
use std::fmt::Display;
use std::io;

#[cfg(windows)]
use crossterm_utils::supports_ansi;
Expand Down Expand Up @@ -67,7 +66,7 @@ impl TerminalColor {

/// Get available color count.
/// (This does not always provide a good result.)
pub fn get_available_color_count(&self) -> io::Result<u16> {
pub fn get_available_color_count(&self) -> Result<u16> {
use std::env;
Ok(match env::var_os("TERM") {
Some(val) => {
Expand Down
3 changes: 1 addition & 2 deletions crossterm_style/src/winapi_color.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! This is a `WinApi` specific implementation for styling related action.
//! This module is used for non supporting `ANSI` Windows terminals.

use std::io;
use std::sync::Once;

use winapi::um::wincon;
Expand Down Expand Up @@ -173,7 +172,7 @@ fn color_value(color: Colored) -> String {
winapi_color.to_string()
}

fn init_console_color() -> io::Result<()> {
fn init_console_color() -> Result<()> {
let screen_buffer = ScreenBuffer::current()?;

let attr = screen_buffer.info()?.attributes();
Expand Down
3 changes: 1 addition & 2 deletions crossterm_utils/src/command.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use std::fmt::Display;
use std::io::Write;

use crate::Result;
use crate::{execute, impl_display, queue, write_cout};
use crate::{execute, impl_display, queue, write_cout, Result};

/// A command is an action that can be performed on the terminal.
///
Expand Down
Loading