From 59cd60674c1d7eacee606a8ff90567b9e58a94f2 Mon Sep 17 00:00:00 2001 From: Raphael Druon Date: Thu, 11 May 2023 07:01:28 -0600 Subject: [PATCH] Handle newline in msg and empty msg --- src/draw_target.rs | 14 +++++++++----- src/state.rs | 8 +++++++- tests/render.rs | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/src/draw_target.rs b/src/draw_target.rs index 3fdd14f5..27c31012 100644 --- a/src/draw_target.rs +++ b/src/draw_target.rs @@ -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 { diff --git a/src/state.rs b/src/state.rs index 1f422ae1..0452f58f 100644 --- a/src/state.rs +++ b/src/state.rs @@ -143,7 +143,13 @@ impl BarState { }; let mut draw_state = drawable.state(); - draw_state.lines.extend(msg.lines().map(Into::into)); + let lines: Vec = 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 diff --git a/tests/render.rs b/tests/render.rs index 08784ec4..ef81c896 100644 --- a/tests/render.rs +++ b/tests/render.rs @@ -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" + ); +}