Skip to content

Commit d81515b

Browse files
committed
correct handling of ANSI control character display lengths
1 parent 0e70616 commit d81515b

File tree

3 files changed

+14
-4
lines changed

3 files changed

+14
-4
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* `0.9.5`:
33
- Bugfixes:
44
- Fixed the problem of `ProgressState` not being public, thus making `setEtaFunction` useless (#147, PR #146). Thanks @deejgregor, @natanfudge !
5+
- Correct handling of ANSI control characters in calculating the display length.
56
- New functionalities:
67
- Added a new `UNICODE_COLORFUL_BAR` style.
78
* `0.9.4`:

src/main/java/me/tongfei/progressbar/ProgressState.java

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,17 @@ public class ProgressState {
2121
long current;
2222
long max;
2323

24-
Instant startInstant = null;
25-
Duration elapsedBeforeStart = Duration.ZERO;
24+
Instant startInstant;
25+
Duration elapsedBeforeStart;
2626

2727
volatile boolean alive = true;
2828
volatile boolean paused = false;
2929

3030
ProgressState(String taskName, long initialMax, long startFrom, Duration elapsedBeforeStart) {
3131
this.taskName = taskName;
32-
if (initialMax < 0) indefinite = true;
32+
if (initialMax < 0)
33+
indefinite = true;
34+
else this.max = initialMax;
3335
this.start = startFrom;
3436
this.current = startFrom;
3537

src/main/java/me/tongfei/progressbar/StringDisplayUtils.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ static int getCharDisplayLength(char c) {
2424
static int getStringDisplayLength(String s) {
2525
int displayWidth = 0;
2626
for (int i = 0; i < s.length(); i++)
27-
displayWidth += getCharDisplayLength(s.charAt(i));
27+
if (s.charAt(i) == '\033') { // skip ANSI escape sequences
28+
while (i < s.length() && s.charAt(i) != 'm') i++;
29+
}
30+
else displayWidth += getCharDisplayLength(s.charAt(i));
2831
return displayWidth;
2932
}
3033

@@ -35,6 +38,10 @@ static String trimDisplayLength(String s, int maxDisplayLength) {
3538

3639
int totalLength = 0;
3740
for (int i = 0; i < s.length(); i++) {
41+
if (s.charAt(i) == '\033') { // skip ANSI escape sequences
42+
while (i < s.length() && s.charAt(i) != 'm') i++;
43+
i++; // skip the 'm' character
44+
}
3845
totalLength += getCharDisplayLength(s.charAt(i));
3946
if (totalLength > maxDisplayLength) {
4047
return s.substring(0, i);

0 commit comments

Comments
 (0)