7
7
import java .util .*;
8
8
9
9
import static java .lang .String .format ;
10
+ import static org .fusesource .jansi .internal .CLibrary .STDOUT_FILENO ;
11
+ import static org .fusesource .jansi .internal .CLibrary .isatty ;
10
12
import static org .hydev .mcpm .utils .GeneralUtils .safeSleep ;
11
13
12
14
/**
@@ -20,14 +22,16 @@ public class ProgressBar implements AutoCloseable
20
22
private final ConsoleUtils cu ;
21
23
private final ProgressBarTheme theme ;
22
24
private final PrintStream out ;
23
- private final int cols ;
25
+ private int cols ;
24
26
25
27
private final List <ProgressRow > activeBars ;
26
28
27
29
private long lastUpdate ;
28
30
29
31
private double frameDelay ;
30
32
33
+ private final boolean istty ;
34
+
31
35
/**
32
36
* Create and initialize a progress bar
33
37
*
@@ -41,11 +45,18 @@ public ProgressBar(ProgressBarTheme theme)
41
45
this .activeBars = new ArrayList <>();
42
46
this .cols = AnsiConsole .getTerminalWidth ();
43
47
48
+ // Default to 70-char width if the width can't be detected (like in a non-tty output)
49
+ if (this .cols == 0 ) this .cols = 70 ;
50
+
44
51
// Last update time
45
52
this .lastUpdate = System .nanoTime ();
46
53
47
54
// Default frame delay is 0.01666 (60 fps)
48
55
this .frameDelay = 1 / 60d ;
56
+
57
+ // Check if output is a TTY. If not, change frame rate to 0.5 fps to avoid spamming a log.
58
+ this .istty = isatty (STDOUT_FILENO ) == 0 ;
59
+ if (istty ) this .frameDelay = 1 / 0.5 ;
49
60
}
50
61
51
62
/**
@@ -79,7 +90,7 @@ protected void update()
79
90
private void forceUpdate ()
80
91
{
81
92
// Roll back to the first line
82
- cu .curUp (activeBars .size ());
93
+ if ( istty ) cu .curUp (activeBars .size ());
83
94
activeBars .forEach (bar -> out .println (bar .toString (theme , cols )));
84
95
}
85
96
@@ -142,7 +153,7 @@ public static void main(String[] args)
142
153
for (int i = 0 ; i < 1300 ; i ++)
143
154
{
144
155
if (i < 1000 && i % 100 == 0 )
145
- all .add (b .appendBar (new ProgressRow (300 ).unit ("MB" ).desc (format ("File %s.tar.gz" , all .size ()))).descLen (40 ));
156
+ all .add (b .appendBar (new ProgressRow (300 ).unit ("MB" ).desc (format ("File %s.tar.gz" , all .size ()))).descLen (30 ));
146
157
all .forEach (a -> a .increase (1 ));
147
158
safeSleep (3 );
148
159
}
0 commit comments