Added output type to `Spin`, same as `Bar`.

TODO: As should change creation interface of `Bar` to take `T` instead of `impl Into<T>`; otherwise, return type deduction of `T` fails. The `impl Into<T> + AsRawFd` creation functions should be moved into another `impl<T: ... + AsRawFd>` block and take `T` directly.

Fortune for termprogress's current commit: Curse − 凶
master
Avril 9 months ago
parent f1eadd0104
commit 5147a1b0dc
Signed by: flanchan
GPG Key ID: 284488987C31F630

@ -2,7 +2,7 @@
name = "termprogress"
description = "A terminal progress bar renderer with status and spinners"
license = "GPL-3.0-or-later"
version = "0.9.1"
version = "0.10.0"
authors = ["Avril <flanchan@cumallover.me>"]
edition = "2018"

@ -49,6 +49,8 @@ fn terminal_size_of(f: &(impl AsRawFd + ?Sized)) -> Option<(terminal_size::Width
terminal_size::terminal_size_using_fd(f.as_raw_fd())
}
use atomic_refcell::AtomicRefCell;
//#[cfg(feature="size")] TODO: How to add `AsRawFd` bound to `Bar` *only* when `size` feature is enabled?
use std::os::unix::io::*;

@ -5,8 +5,6 @@ use std::{
fmt::Write,
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.
///
/// The bar has a max size, that is usually derived from the size of your terminal (if it can be detected) or can be set yourself, to stop the title line going over the side.
@ -140,8 +138,6 @@ impl Bar {
impl<T: io::Write + AsRawFd> Bar<T>
{
/// Create a new bar `width` long with a title.
pub fn with_title(output: impl Into<T> + AsRawFd, width: usize, title: impl AsRef<str>) -> Self
{
@ -270,7 +266,7 @@ impl<T: ?Sized + io::Write + AsRawFd> Bar<T> {
pub fn fit(&mut self) -> bool
{
#[cfg(feature="size")] {
if let Some((terminal_size::Width(tw), _)) = self.try_get_size() {
if let Some((terminal_size::Width(tw), _)) = terminal_size::terminal_size_using_fd(self.output.get_mut().as_raw_fd()) {
let tw = usize::from(tw);
self.width = if self.width < tw {self.width} else {tw};
self.update_dimensions(tw);
@ -407,13 +403,31 @@ impl<T: ?Sized + io::Write + AsRawFd> Display for Bar<T>
fn set_title(&mut self, from: &str)
{
self.title = from.to_string();
self.refresh();
let (_, max_width) = self.widths();
// self.refresh(), with exclusive access. (XXX: Maybe move this to a non-pub `&mut self` helper function)
let out = self.output.get_mut();
//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 update_dimensions(&mut self, to: usize)
{
self.max_width = to;
self.refresh();
// self.refresh(), with exclusive access. (XXX: Maybe move this to a non-pub `&mut self` helper function)
let out = self.output.get_mut();
//TODO: What to do about I/O errors?
let _ = out.write_all(b"\r")
.and_then(|_| stackalloc::stackalloc(to, 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));
}
}
@ -429,7 +443,17 @@ impl<T: ?Sized + io::Write + AsRawFd> ProgressBar for Bar<T>
self.progress = value;
self.update();
}
self.refresh();
let (_, max_width) = self.widths();
// self.refresh(), with exclusive access. (XXX: Maybe move this to a non-pub `&mut self` helper function)
let out = self.output.get_mut();
//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));
}
}
@ -476,8 +500,8 @@ const _:() = {
mod test
{
use super::*;
#[test]
#[test]
fn rendering_blanking()
{
let mut bar = {
@ -498,4 +522,12 @@ mod test
bar.blank();
bar.complete().unwrap();
}
#[test]
fn creating_non_default_fd() {
#[cfg(feature="size")]
let Some(_): Option<Bar<std::io::Stderr>> = Bar::try_new(std::io::stderr(), super::DEFAULT_SIZE) else { return };
#[cfg(not(feature="size"))]
let _: Bar<std::io::Stderr> = Bar::new(std::io::stderr(), super::DEFAULT_SIZE);
}
}

@ -1,6 +1,7 @@
//! A simple character spinner for bars with no known size
use super::*;
use std::io;
/// A single character spinner with optional title that can be told to spin whenever it wants. It implements `Spinner` trait, and is the default spinner.
///
@ -17,19 +18,83 @@ use super::*;
/// # How it looks
/// It renders in the terminal like:
/// `This is a spinner /`
pub struct Spin
///
/// # 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 `Spin` from more than a single thread, you still safely can.
///
/// 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.
pub struct Spin<T: ?Sized = DefaultOutputDevice>/*<T: ?Sized = DefaultOutputDevice>*/ //TODO: <- implement same as `Bar
{
title: String,
current: char,
chars: wheel::WheelIntoIter,
output: AtomicRefCell<T>,
}
impl Spin
{
/// Create a new spinner with title and wheel.
/// Create a new spinner with title and wheel writing to `stdout`.
///
/// To give it the default wheel, you can pass `whl` `Default::default()` to use the default one.
#[inline]
pub fn with_title_default(title: &str, whl: wheel::Wheel) -> Self
{
Self::with_title(create_default_output_device(), title, whl)
}
/// Create a new blank spinner with a wheel writing to `stdout`.
///
/// # Example
/// ```rust
/// # use termprogress::prelude::*;
/// Spin::new_default(Default::default()); // Create a spinner with the default wheel ('|/-\') that writes to stdout.
/// ```
#[inline]
pub fn new_default(whl: wheel::Wheel) -> Self
{
Self::new(create_default_output_device(), whl)
}
}
impl<T> Spin<T>
{
/// Return the backing write object
#[inline]
pub fn into_inner(self) -> T
{
self.output.into_inner()
}
}
impl<T: ?Sized> Spin<T>
{
/// Get a mutable reference to the inner object
#[inline]
pub fn inner_mut(&mut self) -> &mut T
{
self.output.get_mut()
}
/// Get a shared reference to the inner object
///
/// # Returns
/// `None` is returned if a display operation is currently in progress on another thread.
///
/// ## Operation suspension
/// As long as the returned reference lives, **all** display operations will fail silently, on this thread and any other. This method should be avoided in favour of `&*inner_mut()` when exclusive ownership is avaliable.
#[inline]
pub fn inner(&self) -> Option<atomic_refcell::AtomicRef<'_, T>>
{
self.output.try_borrow().ok()
}
}
impl<T: io::Write> Spin<T>
{
/// Create a new spinner with title and wheel writing to `output`.
///
/// To give it the default wheel, you can pass `whl` `Default::default()` to use the default one.
pub fn with_title(title: &str, whl: wheel::Wheel) -> Self
pub fn with_title(output: T, title: &str, whl: wheel::Wheel) -> Self
{
let mut chars = whl.into_iter();
let current = chars.next().unwrap();
@ -37,16 +102,18 @@ impl Spin
title: title.to_string(),
current,
chars,
output: AtomicRefCell::new(output)
}
}
/// Create a new blank spinner with a wheel
/// Create a new blank spinner with a wheel writing to `output`.
///
/// # Example
/// ```rust
/// # use termprogress::prelude::*;
/// Spin::new(Default::default()); // Create a spinner with the default wheel ('|/-\')
/// Spin::new(std::io::stdout(), Default::default()); // Create a spinner with the default wheel ('|/-\') that writes to stdout.
/// ```
pub fn new(whl: wheel::Wheel) -> Self
pub fn new(output: T, whl: wheel::Wheel) -> Self
{
let mut chars = whl.into_iter();
let current = chars.next().unwrap();
@ -54,18 +121,21 @@ impl Spin
title: String::new(),
current,
chars,
output: output.into()
}
}
/// Consume the spinner and complete it. Removes the spin character.
pub fn complete(self) {
println!("{} ", (8u8 as char));
pub fn complete(self) -> io::Result<()> {
let mut output = self.output.into_inner();
writeln!(&mut output, "{} ", (8u8 as char))
}
/// Consume the spinner and complete it with a message. Removes the spin character and then prints the message.
pub fn complete_with(self, msg: &str)
pub fn complete_with(self, msg: &str) -> io::Result<()>
{
println!("{}{}", (8u8 as char), msg);
let mut output = self.output.into_inner();
writeln!(&mut output, "{}{}", (8u8 as char), msg)
}
}
@ -77,21 +147,32 @@ impl Default for Spin
title: String::new(),
chars: wheel::Wheel::default().into_iter(),
current: '|',
output: AtomicRefCell::new(create_default_output_device())
}
}
}
impl Display for Spin
impl<T: ?Sized + io::Write> Display for Spin<T>
{
fn refresh(&self)
{
print!("\r{} {}", self.title, self.current);
flush!();
let Ok(mut output) = self.output.try_borrow_mut() else { return };
//TODO: What to do about I/O errors?
let _ = write!(&mut output, "\r{} {}", self.title, self.current)
.and_then(move |_| flush!(? output));
}
fn blank(&self)
{
print!("\r{} \r", " ".repeat(self.title.chars().count()));
flush!();
let Ok(mut output) = self.output.try_borrow_mut() else { return };
//TODO: What to do about I/O errors?
let _ = output.write_all(b"\r")
.and_then(|_|
stackalloc::stackalloc(self.title.chars().count(), b' ',
|spaces| output.write_all(spaces)))
.and_then(|_| write!(&mut output, " \r"))
.and_then(move |_| flush!(? output));
}
fn get_title(&self) -> &str
{
@ -99,31 +180,54 @@ impl Display for Spin
}
fn set_title(&mut self, from: &str)
{
self.blank();
//self.blank(), with exclusive access
let mut output = self.output.get_mut();
let size = self.title.chars().count();
let _ = output.write_all(b"\r")
.and_then(|_|
stackalloc::stackalloc(size, b' ',
|spaces| output.write_all(spaces)))
.and_then(|_| write!(&mut output, " \r"))
.and_then(|_| flush!(? output));
self.title = from.to_string();
self.refresh();
//self.refresh(), with exclusive access
let _ = write!(&mut output, "\r{} {}", self.title, self.current)
.and_then(move |_| flush!(? output));
}
fn update_dimensions(&mut self, _to:usize){}
fn update_dimensions(&mut self, _:usize){}
fn println(&self, string: &str)
{
self.blank();
println!("{}", string);
if let Ok(mut output) = self.output.try_borrow_mut() {
//TODO: What to do about I/O errors?
let _ = writeln!(&mut output, "{}", string);
drop(output)
} else {
return;
}
self.refresh();
}
}
impl Spinner for Spin
impl<T: ?Sized + io::Write> Spinner for Spin<T>
{
fn bump(&mut self)
{
self.current = self.chars.next().unwrap();
self.refresh();
let mut output = self.output.get_mut();
let _ = write!(&mut output, "\r{} {}", self.title, self.current)
.and_then(move |_| flush!(? output));
}
}
impl WithTitle for Spin
impl<T: io::Write> WithTitle for Spin<T>
{
#[inline]
fn with_title(self, t: impl AsRef<str>) -> Self
@ -137,11 +241,12 @@ impl WithTitle for Spin
fn add_title(&mut self, t: impl AsRef<str>)
{
self.title = t.as_ref().to_owned();
// Self::with_title(t.as_ref(), Default::default())
// Self::with_title(t.as_ref(), Default::default())
}
#[inline] fn update(&mut self){}
#[inline] fn complete(self)
{
Spin::complete(self)
//TODO: What to do about I/O errors?
let _ = Spin::complete(self);
}
}

Loading…
Cancel
Save