use std::collections::HashMap; use std::fmt::{self, Write}; use std::mem; #[cfg(not(target_arch = "wasm32"))] use std::time::Instant; use console::{measure_text_width, Style}; #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(feature = "unicode-segmentation")] use unicode_segmentation::UnicodeSegmentation; use crate::format::{ BinaryBytes, DecimalBytes, FormattedDuration, HumanBytes, HumanCount, HumanDuration, HumanFloatCount, }; use crate::state::{ProgressState, TabExpandedString, DEFAULT_TAB_WIDTH}; #[derive(Clone)] pub struct ProgressStyle { tick_strings: Vec>, progress_chars: Vec>, template: Template, // how unicode-big each char in progress_chars is char_width: usize, tab_width: usize, pub(crate) format_map: HashMap<&'static str, Box>, } #[cfg(feature = "unicode-segmentation")] fn segment(s: &str) -> Vec> { UnicodeSegmentation::graphemes(s, true) .map(|s| s.into()) .collect() } #[cfg(not(feature = "unicode-segmentation"))] fn segment(s: &str) -> Vec> { s.chars().map(|x| x.to_string().into()).collect() } #[cfg(feature = "unicode-width")] fn measure(s: &str) -> usize { unicode_width::UnicodeWidthStr::width(s) } #[cfg(not(feature = "unicode-width"))] fn measure(s: &str) -> usize { s.chars().count() } /// finds the unicode-aware width of the passed grapheme cluters /// panics on an empty parameter, or if the characters are not equal-width fn width(c: &[Box]) -> usize { c.iter() .map(|s| measure(s.as_ref())) .fold(None, |acc, new| { match acc { None => return Some(new), Some(old) => assert_eq!(old, new, "got passed un-equal width progress characters"), } acc }) .unwrap() } impl ProgressStyle { /// Returns the default progress bar style for bars pub fn default_bar() -> Self { Self::new(Template::from_str("{wide_bar} {pos}/{len}").unwrap()) } /// Returns the default progress bar style for spinners pub fn default_spinner() -> Self { Self::new(Template::from_str("{spinner} {msg}").unwrap()) } /// Sets the template string for the progress bar /// /// Review the [list of template keys](../index.html#templates) for more information. pub fn with_template(template: &str) -> Result { Ok(Self::new(Template::from_str(template)?)) } pub(crate) fn set_tab_width(&mut self, new_tab_width: usize) { self.tab_width = new_tab_width; self.template.set_tab_width(new_tab_width); } fn new(template: Template) -> Self { let progress_chars = segment("█░"); let char_width = width(&progress_chars); Self { tick_strings: "⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈ " .chars() .map(|c| c.to_string().into()) .collect(), progress_chars, char_width, template, format_map: HashMap::default(), tab_width: DEFAULT_TAB_WIDTH, } } /// Sets the tick character sequence for spinners /// /// Note that the last character is used as the [final tick string][Self::get_final_tick_str()]. /// At least two characters are required to provide a non-final and final state. pub fn tick_chars(mut self, s: &str) -> Self { self.tick_strings = s.chars().map(|c| c.to_string().into()).collect(); // Format bar will panic with some potentially confusing message, better to panic here // with a message explicitly informing of the problem assert!( self.tick_strings.len() >= 2, "at least 2 tick chars required" ); self } /// Sets the tick string sequence for spinners /// /// Note that the last string is used as the [final tick string][Self::get_final_tick_str()]. /// At least two strings are required to provide a non-final and final state. pub fn tick_strings(mut self, s: &[&str]) -> Self { self.tick_strings = s.iter().map(|s| s.to_string().into()).collect(); // Format bar will panic with some potentially confusing message, better to panic here // with a message explicitly informing of the problem assert!( self.progress_chars.len() >= 2, "at least 2 tick strings required" ); self } /// Sets the progress characters `(filled, current, to do)` /// /// You can pass more than three for a more detailed display. /// All passed grapheme clusters need to be of equal width. pub fn progress_chars(mut self, s: &str) -> Self { self.progress_chars = segment(s); // Format bar will panic with some potentially confusing message, better to panic here // with a message explicitly informing of the problem assert!( self.progress_chars.len() >= 2, "at least 2 progress chars required" ); self.char_width = width(&self.progress_chars); self } /// Adds a custom key that owns a [`ProgressTracker`] to the template pub fn with_key(mut self, key: &'static str, f: S) -> Self { self.format_map.insert(key, Box::new(f)); self } /// Sets the template string for the progress bar /// /// Review the [list of template keys](../index.html#templates) for more information. pub fn template(mut self, s: &str) -> Result { self.template = Template::from_str(s)?; Ok(self) } fn current_tick_str(&self, state: &ProgressState) -> &str { match state.is_finished() { true => self.get_final_tick_str(), false => self.get_tick_str(state.tick), } } /// Returns the tick string for a given number pub fn get_tick_str(&self, idx: u64) -> &str { &self.tick_strings[(idx as usize) % (self.tick_strings.len() - 1)] } /// Returns the tick string for the finished state pub fn get_final_tick_str(&self) -> &str { &self.tick_strings[self.tick_strings.len() - 1] } fn format_bar(&self, fract: f32, width: usize, alt_style: Option<&Style>) -> BarDisplay<'_> { // The number of clusters from progress_chars to write (rounding down). let width = width / self.char_width; // The number of full clusters (including a fractional component for a partially-full one). let fill = fract * width as f32; // The number of entirely full clusters (by truncating `fill`). let entirely_filled = fill as usize; // 1 if the bar is not entirely empty or full (meaning we need to draw the "current" // character between the filled and "to do" segment), 0 otherwise. let head = usize::from(fill > 0.0 && entirely_filled < width); let cur = if head == 1 { // Number of fine-grained progress entries in progress_chars. let n = self.progress_chars.len().saturating_sub(2); let cur_char = if n <= 1 { // No fine-grained entries. 1 is the single "current" entry if we have one, the "to // do" entry if not. 1 } else { // Pick a fine-grained entry, ranging from the last one (n) if the fractional part // of fill is 0 to the first one (1) if the fractional part of fill is almost 1. n.saturating_sub((fill.fract() * n as f32) as usize) }; Some(cur_char) } else { None }; // Number of entirely empty clusters needed to fill the bar up to `width`. let bg = width.saturating_sub(entirely_filled).saturating_sub(head); let rest = RepeatedStringDisplay { str: &self.progress_chars[self.progress_chars.len() - 1], num: bg, }; BarDisplay { chars: &self.progress_chars, filled: entirely_filled, cur, rest: alt_style.unwrap_or(&Style::new()).apply_to(rest), } } pub(crate) fn format_state( &self, state: &ProgressState, lines: &mut Vec, target_width: u16, ) { let mut cur = String::new(); let mut buf = String::new(); let mut wide = None; let pos = state.pos(); let len = state.len().unwrap_or(pos); for part in &self.template.parts { match part { TemplatePart::Placeholder { key, align, width, truncate, style, alt_style, } => { buf.clear(); if let Some(tracker) = self.format_map.get(key.as_str()) { tracker.write(state, &mut TabRewriter(&mut buf, self.tab_width)); } else { match key.as_str() { "wide_bar" => { wide = Some(WideElement::Bar { alt_style }); buf.push('\x00'); } "bar" => buf .write_fmt(format_args!( "{}", self.format_bar( state.fraction(), width.unwrap_or(20) as usize, alt_style.as_ref(), ) )) .unwrap(), "spinner" => buf.push_str(self.current_tick_str(state)), "wide_msg" => { wide = Some(WideElement::Message { align }); buf.push('\x00'); } "msg" => buf.push_str(state.message.expanded()), "prefix" => buf.push_str(state.prefix.expanded()), "pos" => buf.write_fmt(format_args!("{pos}")).unwrap(), "human_pos" => { buf.write_fmt(format_args!("{}", HumanCount(pos))).unwrap(); } "len" => buf.write_fmt(format_args!("{len}")).unwrap(), "human_len" => { buf.write_fmt(format_args!("{}", HumanCount(len))).unwrap(); } "percent" => buf .write_fmt(format_args!("{:.*}", 0, state.fraction() * 100f32)) .unwrap(), "bytes" => buf.write_fmt(format_args!("{}", HumanBytes(pos))).unwrap(), "total_bytes" => { buf.write_fmt(format_args!("{}", HumanBytes(len))).unwrap(); } "decimal_bytes" => buf .write_fmt(format_args!("{}", DecimalBytes(pos))) .unwrap(), "decimal_total_bytes" => buf .write_fmt(format_args!("{}", DecimalBytes(len))) .unwrap(), "binary_bytes" => { buf.write_fmt(format_args!("{}", BinaryBytes(pos))).unwrap(); } "binary_total_bytes" => { buf.write_fmt(format_args!("{}", BinaryBytes(len))).unwrap(); } "elapsed_precise" => buf .write_fmt(format_args!("{}", FormattedDuration(state.elapsed()))) .unwrap(), "elapsed" => buf .write_fmt(format_args!("{:#}", HumanDuration(state.elapsed()))) .unwrap(), "per_sec" => buf .write_fmt(format_args!("{}/s", HumanFloatCount(state.per_sec()))) .unwrap(), "bytes_per_sec" => buf .write_fmt(format_args!("{}/s", HumanBytes(state.per_sec() as u64))) .unwrap(), "binary_bytes_per_sec" => buf .write_fmt(format_args!( "{}/s", BinaryBytes(state.per_sec() as u64) )) .unwrap(), "eta_precise" => buf .write_fmt(format_args!("{}", FormattedDuration(state.eta()))) .unwrap(), "eta" => buf .write_fmt(format_args!("{:#}", HumanDuration(state.eta()))) .unwrap(), "duration_precise" => buf .write_fmt(format_args!("{}", FormattedDuration(state.duration()))) .unwrap(), "duration" => buf .write_fmt(format_args!("{:#}", HumanDuration(state.duration()))) .unwrap(), _ => (), } }; match width { Some(width) => { let padded = PaddedStringDisplay { str: &buf, width: *width as usize, align: *align, truncate: *truncate, }; match style { Some(s) => cur .write_fmt(format_args!("{}", s.apply_to(padded))) .unwrap(), None => cur.write_fmt(format_args!("{padded}")).unwrap(), } } None => match style { Some(s) => cur.write_fmt(format_args!("{}", s.apply_to(&buf))).unwrap(), None => cur.push_str(&buf), }, } } TemplatePart::Literal(s) => cur.push_str(s.expanded()), TemplatePart::NewLine => { self.push_line(lines, &mut cur, state, &mut buf, target_width, &wide); } } } if !cur.is_empty() { self.push_line(lines, &mut cur, state, &mut buf, target_width, &wide); } } fn push_line( &self, lines: &mut Vec, cur: &mut String, state: &ProgressState, buf: &mut String, target_width: u16, wide: &Option, ) { let expanded = match wide { Some(inner) => inner.expand(mem::take(cur), self, state, buf, target_width), None => mem::take(cur), }; // If there are newlines, we need to split them up // and add the lines separately so that they're counted // correctly on re-render. for (i, line) in expanded.split('\n').enumerate() { // No newlines found in this case if i == 0 && line.len() == expanded.len() { lines.push(expanded); break; } lines.push(line.to_string()); } } } struct TabRewriter<'a>(&'a mut dyn fmt::Write, usize); impl Write for TabRewriter<'_> { fn write_str(&mut self, s: &str) -> fmt::Result { self.0 .write_str(s.replace('\t', &" ".repeat(self.1)).as_str()) } } #[derive(Clone, Copy)] enum WideElement<'a> { Bar { alt_style: &'a Option