@ -5,6 +5,7 @@ use std::{
fmt ::Write ,
fmt ::Write ,
io ,
io ,
} ;
} ;
use atomic_refcell ::AtomicRefCell ;
/// A progress bar with a size and optionally title. It implements the `ProgressBar` trait, and is the default progress bar.
/// A progress bar with a size and optionally title. It implements the `ProgressBar` trait, and is the default progress bar.
///
///
@ -23,9 +24,17 @@ use std::{
/// # How it looks
/// # How it looks
/// It renders in the terminal like:
/// It renders in the terminal like:
/// `[========================= ]: 50% this is a title that may get cut if it reaches max le...`
/// `[========================= ]: 50% this is a title that may get cut if it reaches max le...`
///
/// # Thread `Sync`safety
/// This type is safely `Sync` (where `T` is), the behaviour is defined to prevent overlapping writes to `T`.
/// Though it is *advised* to not render a `Bar` from more than a single thread, you still safely can.
///
/// Rendering functions should not be called on multiple threads at the same time, though it is safe to do so.
/// A thread-sync'd rendering operation will safetly (and silently) give up before writing if another thread is already engaging in one.
///
/// A display operation on one thread will cause any other threads attempting on to silently and safely abort their display attempt before anything is written to output.
#[ derive(Debug) ]
#[ derive(Debug) ]
pub struct Bar < T : ? Sized = io ::Stdout > //TODO: Implement this after try_new(), WINCH, etc
pub struct Bar < T : ? Sized = DefaultOutputDevice>
{
{
width : usize ,
width : usize ,
max_width : usize ,
max_width : usize ,
@ -34,7 +43,9 @@ pub struct Bar<T: ?Sized = io::Stdout> //TODO: Implement this after try_new(), W
title : String ,
title : String ,
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
fit_to_term : bool ,
fit_to_term : bool ,
output : T
// Allowing `Bar` to manage the sync will ensure that the bar is not interrupted by another bar-related write, and so any accidental inter-thread corrupting writes will not be drawn (unlike if we relied on `T`'s sync, since we have multiple `write()` calls when rendering and blanking.) *NOTE*: using `AtomicRefCell` i think is actually still be preferable for those reasons. If `T` can be shared and written to with internal sync (like stdout/err,) then non-`Bar` writes are not affected, but `Bar` writes are better contained.
output : AtomicRefCell < T >
}
}
/// The default size of the terminal bar when the programmer does not provide her own.
/// The default size of the terminal bar when the programmer does not provide her own.
@ -45,27 +56,101 @@ pub const DEFAULT_SIZE: usize = 50;
/// Or if `size` is not used.
/// Or if `size` is not used.
pub const DEFAULT_MAX_BORDER_SIZE : usize = 20 ;
pub const DEFAULT_MAX_BORDER_SIZE : usize = 20 ;
impl < T : Default > Default for Bar < T >
/*
impl < T : Default + io ::Write > Default for Bar < T >
{
#[ inline ]
fn default ( ) -> Self
{
Self ::new ( T ::default ( ) , DEFAULT_SIZE )
}
}
* /
impl Default for Bar
{
{
#[ inline ]
#[ inline ]
fn default ( ) -> Self
fn default ( ) -> Self
{
{
Self ::new ( T ::default ( ) , DEFAULT_SIZE )
Self ::new _default( DEFAULT_SIZE )
}
}
}
}
impl < T > Bar < T >
impl Bar {
/// Create a new bar `width` long with a title using the default output descriptor `stdout`.
#[ inline ]
pub fn with_title_default ( width : usize , title : impl AsRef < str > ) -> Self
{
Self ::with_title ( create_default_output_device ( ) , width , title )
}
/// Attempt to create a new bar with max display width of our terminal and a title.
///
/// If `stdout` is not a terminal, then `None` is returned.
#[ cfg(feature= " size " ) ]
#[ inline ]
pub fn try_new_with_title_default ( width : usize , title : impl AsRef < str > ) -> Option < Self >
{
Self ::try_new_with_title ( create_default_output_device ( ) , width , title )
}
/// Create a new bar with max display width of our terminal
///
/// # Notes
/// Without feature `size`, will be the same as `Self::with_max(width, width +20)`
///
/// To try to create one that always adheres to `size`, use the `try_new()` family of functions.
#[ inline ]
pub fn new_default ( width : usize ) -> Self
{
Self ::new ( create_default_output_device ( ) , width )
}
/// Attempt to create a new bar with max display width of our terminal.
///
/// If `stdout` is not a terminal, then `None` is returned.
#[ cfg(feature= " size " ) ]
#[ inline ]
pub fn try_new_default ( width : usize ) -> Option < Self >
{
Self ::try_new ( create_default_output_device ( ) , width )
}
/// Attempt to create a new bar with max display width of our terminal.
///
/// If `stdout` is not a terminal, then `None` is returned.
#[ cfg(feature= " size " ) ]
#[ inline ]
pub fn try_new_default_size_default ( ) -> Option < Self >
{
Self ::try_new_default_size ( create_default_output_device ( ) )
}
/// Create a bar with a max display width
///
/// # Panics
/// If `width` is larger than or equal to `max_width`.
#[ inline ]
pub fn with_max_default ( width : usize , max_width : usize ) -> Self
{
Self ::with_max ( create_default_output_device ( ) , width , max_width )
}
}
impl < T : io ::Write + AsRawFd > Bar < T >
{
{
/// Create a new bar `width` long with a title.
/// Create a new bar `width` long with a title.
pub fn with_title ( output : impl Into < T > , width : usize , title : impl AsRef < str > ) -> Self
pub fn with_title ( output : impl Into < T > + AsRawFd , width : usize , title : impl AsRef < str > ) -> Self
{
{
let mut this = Self ::new ( output , width ) ;
let mut this = Self ::new ( output , width ) ;
this . set_title ( title . as_ref ( ) ) ;
this . add_title ( title . as_ref ( ) ) ;
this . update ( ) ;
this
this
}
}
#[ inline ] fn add_title ( & mut self , title : & str )
#[ inline (always) ] fn add_title ( & mut self , title : & str )
{
{
self . set_title ( title ) ;
self . set_title ( title ) ;
self . update ( )
self . update ( )
@ -73,11 +158,11 @@ impl<T> Bar<T>
/// Attempt to create a new bar with max display width of our terminal and a title.
/// Attempt to create a new bar with max display width of our terminal and a title.
///
///
/// If ` std out` is not a terminal, then `None` is returned.
/// If ` outp ut` is not a terminal, then `None` is returned.
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
pub fn try_new_with_title ( output : impl Into < T > , width : usize , title : impl AsRef < str > ) -> Option < Self >
pub fn try_new_with_title ( output : impl Into < T > + AsRawFd , width : usize , title : impl AsRef < str > ) -> Option < Self >
{
{
let ( terminal_size ::Width ( tw ) , _ ) = terminal_size ::terminal_size ( ) ? ;
let ( terminal_size ::Width ( tw ) , _ ) = terminal_size _of( & output ) ? ;
let tw = usize ::from ( tw ) ;
let tw = usize ::from ( tw ) ;
let mut o = Self ::with_max ( output . into ( ) , if width < tw { width } else { tw } , tw ) ;
let mut o = Self ::with_max ( output . into ( ) , if width < tw { width } else { tw } , tw ) ;
o . set_title ( title . as_ref ( ) ) ;
o . set_title ( title . as_ref ( ) ) ;
@ -100,11 +185,11 @@ impl<T> Bar<T>
///
///
/// To try to create one that always adheres to `size`, use the `try_new()` family of functions.
/// To try to create one that always adheres to `size`, use the `try_new()` family of functions.
#[ cfg_attr(not(feature= " size " ), inline) ]
#[ cfg_attr(not(feature= " size " ), inline) ]
pub fn new ( output : impl Into < T > , width : usize ) -> Self
pub fn new ( output : impl Into < T > + AsRawFd , width : usize ) -> Self
{
{
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
return {
return {
if let Some ( ( terminal_size ::Width ( tw ) , _ ) ) = terminal_size ::terminal_size ( ) {
if let Some ( ( terminal_size ::Width ( tw ) , _ ) ) = terminal_size _of( & output ) {
let tw = usize ::from ( tw ) ;
let tw = usize ::from ( tw ) ;
let mut o = Self ::with_max ( output . into ( ) , if width < tw { width } else { tw } , tw ) ;
let mut o = Self ::with_max ( output . into ( ) , if width < tw { width } else { tw } , tw ) ;
o . fit_to_term = true ;
o . fit_to_term = true ;
@ -123,23 +208,23 @@ impl<T> Bar<T>
/// Attempt to create a new bar with max display width of our terminal.
/// Attempt to create a new bar with max display width of our terminal.
///
///
/// If ` std out` is not a terminal, then `None` is returned.
/// If ` outp ut` is not a terminal, then `None` is returned.
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
pub fn try_new ( output : impl Into < T > , width : usize ) -> Option < Self >
pub fn try_new ( output : impl Into < T > + AsRawFd , width : usize ) -> Option < Self >
{
{
let ( terminal_size ::Width ( tw ) , _ ) = terminal_size ::terminal_size ( ) ? ;
let ( terminal_size ::Width ( tw ) , _ ) = terminal_size _of( & output ) ? ;
let tw = usize ::from ( tw ) ;
let tw = usize ::from ( tw ) ;
let mut o = Self ::with_max ( output , if width < tw { width } else { tw } , tw ) ;
let mut o = Self ::with_max ( output .into ( ) , if width < tw { width } else { tw } , tw ) ;
o . fit_to_term = true ;
o . fit_to_term = true ;
Some ( o )
Some ( o )
}
}
/// Attempt to create a new bar with max display width of our terminal.
/// Attempt to create a new bar with max display width of our terminal.
///
///
/// If ` std out` is not a terminal, then `None` is returned.
/// If ` outp ut` is not a terminal, then `None` is returned.
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
#[ inline ]
#[ inline ]
pub fn try_new_default_size ( to : impl Into < T > ) -> Option < Self >
pub fn try_new_default_size ( to : impl Into < T > + AsRawFd ) -> Option < Self >
{
{
Self ::try_new ( to , DEFAULT_SIZE )
Self ::try_new ( to , DEFAULT_SIZE )
}
}
@ -148,7 +233,7 @@ impl<T> Bar<T>
///
///
/// # Panics
/// # Panics
/// If `width` is larger than or equal to `max_width`.
/// If `width` is larger than or equal to `max_width`.
pub fn with_max ( output : T, width : usize , max_width : usize ) -> Self
pub fn with_max ( output : impl Into < T> , width : usize , max_width : usize ) -> Self
{
{
let mut this = Self {
let mut this = Self {
width ,
width ,
@ -158,7 +243,7 @@ impl<T> Bar<T>
title : String ::with_capacity ( max_width - width ) ,
title : String ::with_capacity ( max_width - width ) ,
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
fit_to_term : false ,
fit_to_term : false ,
output
output : AtomicRefCell ::new ( output . into ( ) )
} ;
} ;
this . update ( ) ;
this . update ( ) ;
this
this
@ -166,20 +251,31 @@ impl<T> Bar<T>
}
}
impl < T : ? Sized > Bar < T > {
impl < T : ? Sized + io ::Write + AsRawFd > Bar < T > {
#[ inline(always) ]
#[ cfg(feature= " size " ) ]
fn try_get_size ( & self ) -> Option < ( terminal_size ::Width , terminal_size ::Height ) >
{
let b = self . output . try_borrow ( ) . ok ( ) ? ;
terminal_size ::terminal_size_using_fd ( b . as_raw_fd ( ) )
}
/// Fit to terminal's width if possible.
/// Fit to terminal's width if possible.
///
///
/// # Notes
/// # Notes
/// Available with feature `size` only.
/// Available with feature `size` only.
///
/// # Returns
/// If the re-fit succeeded.
/// A `fit()` will also fail if another thread is already engaging in a display operation.
pub fn fit ( & mut self ) -> bool
pub fn fit ( & mut self ) -> bool
{
{
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ] {
if let Some ( ( terminal_size ::Width ( tw ) , _ ) ) = terminal_size ::terminal_size ( ) {
if let Some ( ( terminal_size ::Width ( tw ) , _ ) ) = self . try_get_size ( ) {
let tw = usize ::from ( tw ) ;
let tw = usize ::from ( tw ) ;
self . width = if self . width < tw { self . width } else { tw } ;
self . width = if self . width < tw { self . width } else { tw } ;
self . update_dimensions ( tw ) ;
self . update_dimensions ( tw ) ;
return true ;
return true ;
}
}
}
false
false
}
}
@ -188,7 +284,7 @@ impl<T: ?Sized> Bar<T> {
{
{
#[ cfg(feature= " size " ) ]
#[ cfg(feature= " size " ) ]
if self . fit_to_term {
if self . fit_to_term {
if let Some ( ( terminal_size ::Width ( tw ) , _ ) ) = terminal_size ::terminal _size( ) {
if let Some ( ( terminal_size ::Width ( tw ) , _ ) ) = self . try_get _size( ) {
let tw = usize ::from ( tw ) ;
let tw = usize ::from ( tw ) ;
let width = if self . width < tw { self . width } else { tw } ;
let width = if self . width < tw { self . width } else { tw } ;
return ( width , tw ) ;
return ( width , tw ) ;
@ -213,10 +309,12 @@ impl<T: ?Sized> Bar<T> {
}
}
}
}
}
impl < T : io ::Write > Bar < T > {
/// Consume the bar and complete it, regardless of progress.
/// Consume the bar and complete it, regardless of progress.
pub fn complete ( self )
pub fn complete ( self ) -> io ::Result < ( ) >
{
{
println!( "" ) ;
writeln!( & mut self . output . into_inner ( ) , "" )
}
}
}
}
@ -265,25 +363,40 @@ fn ensure_lower(input: String, to: usize) -> String
}
}
}
}
impl < T : ? Sized + io ::Write > Display for Bar < T >
impl < T : ? Sized + io ::Write + AsRawFd > Display for Bar < T >
{
{
fn refresh ( & self )
fn refresh ( & self )
{
{
let ( _ , max_width ) = self . widths ( ) ;
let ( _ , max_width ) = self . widths ( ) ;
let temp = format! ( "[{}]: {:.2}%" , self . buffer , self . progress * 100.00 ) ;
let temp = format! ( "[{}]: {:.2}%" , self . buffer , self . progress * 100.00 ) ;
let title = ensure_lower ( format! ( " {}" , self . title ) , max_width - temp . chars ( ) . count ( ) ) ;
let title = ensure_lower ( format! ( " {}" , self . title ) , max_width - temp . chars ( ) . count ( ) ) ;
let temp = ensure_eq ( format! ( "{}{}" , temp , title ) , max_width ) ;
let temp = ensure_eq ( format! ( "{}{}" , temp , title ) , max_width ) ;
print! ( "\x1B[0m\x1B[K{}" , temp ) ;
print! ( "\n\x1B[1A" ) ;
// If another thread is writing, just abort (XXX: Is this the best way to handle it?)
flush ! ( ) ;
//
// We acquire the lock after work allocation and computation to keep it for the shortest amount of time, this is an acceptible tradeoff since multiple threads shouldn't be calling this at once anyway.
let Ok ( mut out ) = self . output . try_borrow_mut ( ) else { return } ;
//TODO: What to do about I/O errors?
let _ = write! ( out , "\x1B[0m\x1B[K{}" , temp ) // XXX: For now, just abort if one fails.
. and_then ( | _ | write! ( out , "\n\x1B[1A" ) )
. and_then ( move | _ | flush ! ( ? out ) ) ;
}
}
fn blank ( & self )
fn blank ( & self )
{
{
let ( _ , max_width ) = self . widths ( ) ;
let ( _ , max_width ) = self . widths ( ) ;
print! ( "\r{}\r" , " " . repeat ( max_width ) ) ;
flush ! ( ) ;
// If another thread is writing, just abort (XXX: Is this the best way to handle it?)
let Ok ( mut out ) = self . output . try_borrow_mut ( ) else { return } ;
//TODO: What to do about I/O errors?
let _ = out . write_all ( b" \r " )
. and_then ( | _ | stackalloc ::stackalloc ( max_width , b' ' , | spaces | out . write_all ( spaces ) ) ) // Write `max_width` spaces (TODO: Is there a better way to do this? With no allocation? With a repeating iterator maybe?)
. and_then ( | _ | out . write_all ( b" \r " ) )
. and_then ( move | _ | flush ! ( ? out ) ) ;
}
}
fn get_title ( & self ) -> & str
fn get_title ( & self ) -> & str
@ -304,7 +417,7 @@ impl<T: ?Sized + io::Write> Display for Bar<T>
}
}
}
}
impl < T : ? Sized + io ::Write > ProgressBar for Bar < T >
impl < T : ? Sized + io ::Write + AsRawFd > ProgressBar for Bar < T >
{
{
fn get_progress ( & self ) -> f64
fn get_progress ( & self ) -> f64
{
{
@ -320,7 +433,7 @@ impl<T: ?Sized + io::Write> ProgressBar for Bar<T>
}
}
}
}
impl < T : io ::Write > WithTitle for Bar < T >
impl < T : io ::Write + AsRawFd > WithTitle for Bar < T >
{
{
fn add_title ( & mut self , string : impl AsRef < str > )
fn add_title ( & mut self , string : impl AsRef < str > )
{
{
@ -332,7 +445,8 @@ impl<T: io::Write> WithTitle for Bar<T>
}
}
fn complete ( self )
fn complete ( self )
{
{
self . complete ( ) ;
//TODO: What to do about I/O errors?
let _ = self . complete ( ) ;
}
}
}
}
@ -357,3 +471,31 @@ const _:() = {
assert_is_bar ! ( std ::fs ::File ) ;
assert_is_bar ! ( std ::fs ::File ) ;
}
}
} ;
} ;
#[ cfg(test) ]
mod test
{
use super ::* ;
#[ test ]
fn rendering_blanking ( )
{
let mut bar = {
#[ cfg(feature= " size " ) ]
let Some ( bar ) = Bar ::try_new_default_size_default ( ) else { return } ;
#[ cfg(not(feature= " size " )) ]
let bar = Bar ::new_default ( 50 ) ;
bar
} ;
bar . set_progress ( 0.5 ) ;
bar . blank ( ) ;
bar . set_progress ( 0.7 ) ;
bar . set_title ( "70 percent." ) ;
bar . refresh ( ) ;
//println!();
bar . set_progress ( 0.2 ) ;
bar . set_title ( "..." ) ;
bar . blank ( ) ;
bar . complete ( ) . unwrap ( ) ;
}
}