Skip to content

Commit

Permalink
Handle newline in msg and empty msg
Browse files Browse the repository at this point in the history
  • Loading branch information
RDruon authored and chris-laplante committed May 11, 2023
1 parent 6d31845 commit 59cd606
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 6 deletions.
14 changes: 9 additions & 5 deletions src/draw_target.rs
Expand Up @@ -496,11 +496,15 @@ impl DrawState {
let len = self.lines.len();
let mut real_len = 0;
for (idx, line) in self.lines.iter().enumerate() {
// Calculate real length based on terminal width
// This take in account linewrap from terminal
real_len +=
(console::measure_text_width(line) as f64 / term.width() as f64).ceil() as usize;

if line.is_empty() {
// Empty line are new line
real_len += 1;
} else {
// Calculate real length based on terminal width
// This take in account linewrap from terminal
real_len += (console::measure_text_width(line) as f64 / term.width() as f64).ceil()
as usize;
}
if idx + 1 != len {
term.write_line(line)?;
} else {
Expand Down
8 changes: 7 additions & 1 deletion src/state.rs
Expand Up @@ -143,7 +143,13 @@ impl BarState {
};

let mut draw_state = drawable.state();
draw_state.lines.extend(msg.lines().map(Into::into));
let lines: Vec<String> = msg.lines().map(Into::into).collect();
// Empty msg should trigger newline as we are in println
if lines.is_empty() {
draw_state.lines.push(String::new());
} else {
draw_state.lines.extend(lines);
}
draw_state.orphan_lines_count = draw_state.lines.len();
if !matches!(self.state.status, Status::DoneHidden) {
self.style
Expand Down
39 changes: 39 additions & 0 deletions tests/render.rs
Expand Up @@ -1044,3 +1044,42 @@ n terminal width"#
.trim()
);
}

#[test]
fn basic_progress_bar_newline() {
let in_mem = InMemoryTerm::new(10, 80);
let pb = ProgressBar::with_draw_target(
Some(10),
ProgressDrawTarget::term_like(Box::new(in_mem.clone())),
);

assert_eq!(in_mem.contents(), String::new());

pb.println("\nhello");
pb.tick();
assert_eq!(
in_mem.contents(),
r#"
hello
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 0/10"#
);

pb.inc(1);
pb.println("");
assert_eq!(
in_mem.contents(),
r#"
hello
███████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ 1/10"#
);

pb.finish();
assert_eq!(
in_mem.contents(),
"
hello
██████████████████████████████████████████████████████████████████████████ 10/10"
);
}

0 comments on commit 59cd606

Please sign in to comment.