use std::fmt::Display;
use std::io;
use std::io::Write;
use std::sync::{Arc, Mutex};
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, RawFd};
#[cfg(windows)]
use std::os::windows::io::{AsRawHandle, RawHandle};
use crate::{kb::Key, utils::Style};
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TermTarget {
Stdout,
Stderr,
}
#[derive(Debug)]
pub struct TermInner {
target: TermTarget,
buffer: Option<Mutex<Vec<u8>>>,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TermFamily {
File,
UnixTerm,
WindowsConsole,
Dummy,
}
#[derive(Debug, Clone)]
pub struct TermFeatures<'a>(&'a Term);
impl<'a> TermFeatures<'a> {
#[inline]
pub fn is_attended(&self) -> bool {
is_a_terminal(self.0)
}
#[inline]
pub fn colors_supported(&self) -> bool {
is_a_color_terminal(self.0)
}
#[inline]
pub fn is_msys_tty(&self) -> bool {
#[cfg(windows)]
{
msys_tty_on(&self.0)
}
#[cfg(not(windows))]
{
false
}
}
#[inline]
pub fn wants_emoji(&self) -> bool {
self.is_attended() && wants_emoji()
}
#[inline]
pub fn family(&self) -> TermFamily {
if !self.is_attended() {
return TermFamily::File;
}
#[cfg(windows)]
{
TermFamily::WindowsConsole
}
#[cfg(unix)]
{
TermFamily::UnixTerm
}
#[cfg(target_arch = "wasm32")]
{
TermFamily::Dummy
}
}
}
#[derive(Clone, Debug)]
pub struct Term {
inner: Arc<TermInner>,
pub(crate) is_msys_tty: bool,
pub(crate) is_tty: bool,
}
impl Term {
fn with_inner(inner: TermInner) -> Term {
let mut term = Term {
inner: Arc::new(inner),
is_msys_tty: false,
is_tty: false,
};
term.is_msys_tty = term.features().is_msys_tty();
term.is_tty = term.features().is_attended();
term
}
#[inline]
pub fn stdout() -> Term {
Term::with_inner(TermInner {
target: TermTarget::Stdout,
buffer: None,
})
}
#[inline]
pub fn stderr() -> Term {
Term::with_inner(TermInner {
target: TermTarget::Stderr,
buffer: None,
})
}
pub fn buffered_stdout() -> Term {
Term::with_inner(TermInner {
target: TermTarget::Stdout,
buffer: Some(Mutex::new(vec![])),
})
}
pub fn buffered_stderr() -> Term {
Term::with_inner(TermInner {
target: TermTarget::Stderr,
buffer: Some(Mutex::new(vec![])),
})
}
#[inline]
pub fn style(&self) -> Style {
match self.target() {
TermTarget::Stderr => Style::new().for_stderr(),
TermTarget::Stdout => Style::new().for_stdout(),
}
}
#[inline]
pub fn target(&self) -> TermTarget {
self.inner.target
}
#[doc(hidden)]
pub fn write_str(&self, s: &str) -> io::Result<()> {
match self.inner.buffer {
Some(ref buffer) => buffer.lock().unwrap().write_all(s.as_bytes()),
None => self.write_through(s.as_bytes()),
}
}
pub fn write_line(&self, s: &str) -> io::Result<()> {
match self.inner.buffer {
Some(ref mutex) => {
let mut buffer = mutex.lock().unwrap();
buffer.extend_from_slice(s.as_bytes());
buffer.push(b'\n');
Ok(())
}
None => self.write_through(format!("{}\n", s).as_bytes()),
}
}
pub fn read_char(&self) -> io::Result<char> {
loop {
match self.read_key()? {
Key::Char(c) => {
return Ok(c);
}
Key::Enter => {
return Ok('\n');
}
Key::Unknown => {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"Not a terminal",
))
}
_ => {}
}
}
}
pub fn read_key(&self) -> io::Result<Key> {
if !self.is_tty {
Ok(Key::Unknown)
} else {
read_single_key()
}
}
pub fn read_line(&self) -> io::Result<String> {
if !self.is_tty {
return Ok("".into());
}
let mut rv = String::new();
io::stdin().read_line(&mut rv)?;
let len = rv.trim_end_matches(&['\r', '\n'][..]).len();
rv.truncate(len);
Ok(rv)
}
pub fn read_line_initial_text(&self, initial: &str) -> io::Result<String> {
if !self.is_tty {
return Ok("".into());
}
self.write_str(initial)?;
let mut chars: Vec<char> = initial.chars().collect();
loop {
match self.read_key()? {
Key::Backspace => {
if chars.pop().is_some() {
self.clear_chars(1)?;
}
self.flush()?;
}
Key::Char(chr) => {
chars.push(chr);
let mut bytes_char = [0; 4];
chr.encode_utf8(&mut bytes_char);
self.write_str(chr.encode_utf8(&mut bytes_char))?;
self.flush()?;
}
Key::Enter => break,
Key::Unknown => {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"Not a terminal",
))
}
_ => (),
}
}
Ok(chars.iter().collect::<String>())
}
pub fn read_secure_line(&self) -> io::Result<String> {
if !self.is_tty {
return Ok("".into());
}
match read_secure() {
Ok(rv) => {
self.write_line("")?;
Ok(rv)
}
Err(err) => Err(err),
}
}
pub fn flush(&self) -> io::Result<()> {
if let Some(ref buffer) = self.inner.buffer {
let mut buffer = buffer.lock().unwrap();
if !buffer.is_empty() {
self.write_through(&buffer[..])?;
buffer.clear();
}
}
Ok(())
}
#[inline]
pub fn is_term(&self) -> bool {
self.is_tty
}
#[inline]
pub fn features(&self) -> TermFeatures<'_> {
TermFeatures(self)
}
#[inline]
pub fn size(&self) -> (u16, u16) {
self.size_checked().unwrap_or((24, DEFAULT_WIDTH))
}
#[inline]
pub fn size_checked(&self) -> Option<(u16, u16)> {
terminal_size(self)
}
#[inline]
pub fn move_cursor_to(&self, x: usize, y: usize) -> io::Result<()> {
move_cursor_to(self, x, y)
}
#[inline]
pub fn move_cursor_up(&self, n: usize) -> io::Result<()> {
move_cursor_up(self, n)
}
#[inline]
pub fn move_cursor_down(&self, n: usize) -> io::Result<()> {
move_cursor_down(self, n)
}
#[inline]
pub fn move_cursor_left(&self, n: usize) -> io::Result<()> {
move_cursor_left(self, n)
}
#[inline]
pub fn move_cursor_right(&self, n: usize) -> io::Result<()> {
move_cursor_right(self, n)
}
#[inline]
pub fn clear_line(&self) -> io::Result<()> {
clear_line(self)
}
pub fn clear_last_lines(&self, n: usize) -> io::Result<()> {
self.move_cursor_up(n)?;
for _ in 0..n {
self.clear_line()?;
self.move_cursor_down(1)?;
}
self.move_cursor_up(n)?;
Ok(())
}
#[inline]
pub fn clear_screen(&self) -> io::Result<()> {
clear_screen(self)
}
#[inline]
pub fn clear_to_end_of_screen(&self) -> io::Result<()> {
clear_to_end_of_screen(self)
}
#[inline]
pub fn clear_chars(&self, n: usize) -> io::Result<()> {
clear_chars(self, n)
}
pub fn set_title<T: Display>(&self, title: T) {
if !self.is_tty {
return;
}
set_title(title);
}
#[inline]
pub fn show_cursor(&self) -> io::Result<()> {
show_cursor(self)
}
#[inline]
pub fn hide_cursor(&self) -> io::Result<()> {
hide_cursor(self)
}
#[cfg(all(windows, feature = "windows-console-colors"))]
fn write_through(&self, bytes: &[u8]) -> io::Result<()> {
if self.is_msys_tty || !self.is_tty {
self.write_through_common(bytes)
} else {
use winapi_util::console::Console;
match self.inner.target {
TermTarget::Stdout => console_colors(self, Console::stdout()?, bytes),
TermTarget::Stderr => console_colors(self, Console::stderr()?, bytes),
}
}
}
#[cfg(not(all(windows, feature = "windows-console-colors")))]
fn write_through(&self, bytes: &[u8]) -> io::Result<()> {
self.write_through_common(bytes)
}
pub(crate) fn write_through_common(&self, bytes: &[u8]) -> io::Result<()> {
match self.inner.target {
TermTarget::Stdout => {
io::stdout().write_all(bytes)?;
io::stdout().flush()?;
}
TermTarget::Stderr => {
io::stderr().write_all(bytes)?;
io::stderr().flush()?;
}
}
Ok(())
}
}
#[inline]
pub fn user_attended() -> bool {
Term::stdout().features().is_attended()
}
#[inline]
pub fn user_attended_stderr() -> bool {
Term::stderr().features().is_attended()
}
#[cfg(unix)]
impl AsRawFd for Term {
fn as_raw_fd(&self) -> RawFd {
match self.inner.target {
TermTarget::Stdout => libc::STDOUT_FILENO,
TermTarget::Stderr => libc::STDERR_FILENO,
}
}
}
#[cfg(windows)]
impl AsRawHandle for Term {
fn as_raw_handle(&self) -> RawHandle {
use winapi::um::processenv::GetStdHandle;
use winapi::um::winbase::{STD_ERROR_HANDLE, STD_OUTPUT_HANDLE};
unsafe {
GetStdHandle(match self.inner.target {
TermTarget::Stdout => STD_OUTPUT_HANDLE,
TermTarget::Stderr => STD_ERROR_HANDLE,
}) as RawHandle
}
}
}
impl io::Write for Term {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self.inner.buffer {
Some(ref buffer) => buffer.lock().unwrap().write_all(buf),
None => self.write_through(buf),
}?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Term::flush(self)
}
}
impl<'a> io::Write for &'a Term {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self.inner.buffer {
Some(ref buffer) => buffer.lock().unwrap().write_all(buf),
None => self.write_through(buf),
}?;
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Term::flush(self)
}
}
impl io::Read for Term {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
io::stdin().read(buf)
}
}
impl<'a> io::Read for &'a Term {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
io::stdin().read(buf)
}
}
#[cfg(unix)]
pub use crate::unix_term::*;
#[cfg(target_arch = "wasm32")]
pub use crate::wasm_term::*;
#[cfg(windows)]
pub use crate::windows_term::*;