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

Add a configurable drop behavior for Spinner #31

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
46 changes: 46 additions & 0 deletions examples/on_drop.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use spinners::{Spinner, Spinners, StopBehavior};

fn frobnicate(should_work: bool) -> Result<(), String> {
if should_work {
Ok(())
} else {
Err("Error!".to_string())
}
}

fn main() -> Result<(), String> {
// Successful variant shows the message from [Spinner::stop_with]
// and not the one from [Spinner::on_drop]
{
println!("Spinner that is stopped after some action is successfully performed:");
let mut sp = Spinner::new(Spinners::Dots, "Frobincating...".into()).on_drop(
StopBehavior::SymbolAndMessage(
"✗",
"Ouch, something went wrong with the Frobnicator!?".into(),
),
);
frobnicate(true)?;
sp.stop_with(&StopBehavior::SymbolAndMessage(
"✔",
"Frobnication successful!".into(),
));
}

// Failure variant in which the Spinner is dropped before having been explicitly
// stopped, the behavior passed into [Spinner::on_drop] is used.
{
println!("Spinner that never reaches a stop call because an error is hit before:");
let mut sp = Spinner::new(Spinners::Dots, "Frobincating...".into()).on_drop(
StopBehavior::SymbolAndMessage(
"✗",
"Ouch, something went wrong with the Frobnicator!?".into(),
),
);
frobnicate(false)?;
sp.stop_with(&StopBehavior::SymbolAndMessage(
"✔",
"Frobnication successful!".into(),
));
}
Ok(())
}
102 changes: 93 additions & 9 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,21 @@ use crate::utils::spinners_data::SPINNERS as SpinnersMap;

mod utils;

pub struct Spinner {
struct SpinnerHandle {
sender: Sender<(Instant, Option<String>)>,
join: Option<JoinHandle<()>>,
join: JoinHandle<()>,
}

pub struct Spinner {
handle: Option<SpinnerHandle>,
on_drop: Option<StopBehavior>,
}

impl Drop for Spinner {
fn drop(&mut self) {
if self.join.is_some() {
self.sender.send((Instant::now(), None)).unwrap();
self.join.take().unwrap().join().unwrap();
if self.handle.is_some() {
let behavior = self.on_drop.take().unwrap();
self.stop_with(&behavior);
}
}
}
Expand Down Expand Up @@ -95,8 +100,8 @@ impl Spinner {
});

Self {
sender,
join: Some(join),
handle: Some(SpinnerHandle { sender, join }),
on_drop: Some(StopBehavior::NewLine),
}
}

Expand Down Expand Up @@ -211,9 +216,88 @@ impl Spinner {
}

fn stop_inner(&mut self, stop_time: Instant, stop_symbol: Option<String>) {
self.sender
let hdl = self.handle.take().unwrap();

hdl.sender
.send((stop_time, stop_symbol))
.expect("Could not stop spinner thread.");
self.join.take().unwrap().join().unwrap();

hdl.join.join().unwrap();
}

/// Builder method to convert a Spinner to a one with a new [StopBehavior].
///
/// If the spinner is dropped without any prior call to one of its `Spinner::stop*`
/// methods, then the [StopBehavior] from the `behavior` parameter is triggered.
///
/// Example:
/// ```
/// use spinners::{Spinner, Spinners, StopBehavior};
///
/// # fn foo() -> Result<(), String> {
/// fn frobnicate(should_work: bool) -> Result<(), String> {
/// if should_work {
/// Ok(())
/// } else {
/// Err("Error!".to_string())
/// }
/// }
///
/// // Successful variant shows the message from [Spinner::stop_with]
/// // and not the one from [Spinner::on_drop]
/// {
/// let mut sp = Spinner::new(Spinners::Dots, "Frobincating...".into())
/// .on_drop(StopBehavior::SymbolAndMessage(
/// "✗",
/// "Ouch, something went wrong with the Frobnicator!?".into()));
/// frobnicate(true)?;
/// sp.stop_with(&StopBehavior::SymbolAndMessage(
/// "✔", "Frobnication successful!".into()));
/// }
///
/// // Failure variant in which the Spinner is dropped before having been explicitly
/// // stopped, the behavior passed into [Spinner::on_drop] is used.
/// {
/// let mut sp = Spinner::new(Spinners::Dots, "Frobincating...".into())
/// .on_drop(StopBehavior::SymbolAndMessage(
/// "✗",
/// "Ouch, something went wrong with the Frobnicator!?".into()));
/// frobnicate(false)?;
/// sp.stop_with(&StopBehavior::SymbolAndMessage(
/// "✔", "Frobnication successful!".into()));
/// }
/// # Ok(())
/// # }
/// ```
pub fn on_drop(mut self, behavior: StopBehavior) -> Self {
let hdl = self.handle.take().unwrap();
Self {
handle: Some(SpinnerHandle {
sender: hdl.sender,
join: hdl.join,
}),
on_drop: Some(behavior),
}
}

/// Stops the spinner with a given `StopBehavior`
///
/// Each StopBehavior matches one of the other `Spinner::stop*` methods.
pub fn stop_with(&mut self, stop_behavior: &StopBehavior) {
match stop_behavior {
StopBehavior::NewLine => self.stop_with_newline(),
StopBehavior::Message(msg) => self.stop_with_message(msg.to_owned()),
StopBehavior::Symbol(symbol) => self.stop_with_symbol(symbol),
StopBehavior::SymbolAndMessage(symbol, msg) => {
self.stop_and_persist(symbol, msg.to_owned())
}
}
}
}

pub enum StopBehavior {
NewLine,
Message(String),
Symbol(&'static str),
SymbolAndMessage(&'static str, String),
}