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

Handle newline in msg and empty msg #540

Merged
merged 1 commit into from
May 11, 2023
Merged
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
14 changes: 9 additions & 5 deletions src/draw_target.rs
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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"
);
}