1 # (X)Emacs mode: -*- cperl -*-
3 package Term::ProgressBar;
5 #XXX TODO Redo original test with count=20
9 # Test use of last_update (with update(*undef*)) with scales
10 # Choice of FH other than STDERR
11 # If no term, output no progress bar; just progress so far
12 # Use of simple term with v2.0 bar
13 # If name is wider than term, trim name
14 # Don't update progress bar on new?
18 Term::ProgressBar - provide a progress meter on a standard terminal
22 use Term::ProgressBar;
24 $progress = Term::ProgressBar->new ({count => $count});
25 $progress->update ($so_far);
29 Term::ProgressBar provides a simple progress bar on the terminal, to let the
30 user know that something is happening, roughly how much stuff has been done,
31 and maybe an estimate at how long remains.
33 A typical use sets up the progress bar with a number of items to do, and then
34 calls L<update|"update"> to update the bar whenever an item is processed.
36 Often, this would involve updating the progress bar many times with no
37 user-visible change. To avoid uneccessary work, the update method returns a
38 value, being the update value at which the user will next see a change. By
39 only calling update when the current value exceeds the next update value, the
40 call overhead is reduced.
42 Remember to call the C<< $progress->update($max_value) >> when the job is done
43 to get a nice 100% done bar.
45 A progress bar by default is simple; it just goes from left-to-right, filling
46 the bar with '=' characters. These are called B<major> characters. For
47 long-running jobs, this may be too slow, so two additional features are
48 available: a linear completion time estimator, and/or a B<minor> character:
49 this is a character that I<moves> from left-to-right on the progress bar (it
50 does not fill it as the major character does), traversing once for each
51 major-character added. This exponentially increases the granularity of the
52 bar for the same width.
56 =head2 A really simple use
60 use Term::ProgressBar 2.00;
62 use constant MAX => 100_000;
64 my $progress = Term::ProgressBar->new(MAX);
68 for(my $i = 0; 2**$i <= $_; $i++) {
74 $progress->update($_);
78 Here is a simple example. The process considers all the numbers between 0 and
79 MAX, and updates the progress bar whenever it finds one. Note that the
80 progress bar update will be very erratic. See below for a smoother example.
81 Note also that the progress bar will never complete; see below to solve this.
83 The complete text of this example is in F<examples/powers> in the
84 distribution set (it is not installed as part of the module).
86 =head2 A smoother bar update
88 my $progress = Term::ProgressBar->new($max);
92 for(my $i = 0; 2**$i <= $_; $i++) {
100 This example calls update for each value considered. This will result in a
101 much smoother progress update, but more program time is spent updating the bar
102 than doing the "real" work. See below to remedy this. This example does
103 I<not> call C<< $progress->update($max); >> at the end, since it is
104 unnecessary, and ProgressBar will throw an exception at an attempt to update a
107 The complete text of this example is in F<examples/powers2> in the
108 distribution set (it is not installed as part of the module.
110 =head2 A (much) more efficient update
112 my $progress = Term::ProgressBar->new({name => 'Powers', count => $max, remove => 1});
118 for(my $i = 0; 2**$i <= $_; $i++) {
123 $next_update = $progress->update($_)
124 if $_ >= $next_update;
126 $progress->update($max)
127 if $max >= $next_update;
129 This example does two things to improve efficiency: firstly, it uses the value
130 returned by L<update|"update"> to only call it again when needed; secondly, it
131 switches off the use of minor characters to update a lot less frequently (C<<
132 $progress->minor(0); >>. The use of the return value of L<update|"update">
133 means that the call of C<< $progress->update($max); >> at the end is required
134 to ensure that the bar ends on 100%, which gives the user a nice feeling.
136 This example also sets the name of the progress bar.
138 This example also demonstrates the use of the 'remove' flag, which removes the
139 progress bar from the terminal when done.
141 The complete text of this example is in F<examples/powers3> in the
142 distribution set (it is not installed as part of the module.
144 =head2 Using Completion Time Estimation
146 my $progress = Term::ProgressBar->new({name => 'Powers',
149 $progress->max_update_rate(1);
154 for(my $i = 0; 2**$i <= $_; $i++) {
157 $progress->message(sprintf "Found %8d to be 2 ** %2d", $_, $i);
161 $next_update = $progress->update($_)
162 if $_ > $next_update;
164 $progress->update($max)
165 if $max >= $next_update;
167 This example uses the L<ETA|"ETA"> option to switch on completion estimation.
168 Also, the update return is tuned to try to update the bar approximately once
169 per second, with the L<max_update_rate|"max_update_rate"> call. See the
170 documentation for the L<new|new> method for details of the format(s) used.
172 This example also provides an example of the use of the L<message|"message">
173 function to output messages to the same filehandle whilst keeping the progress bar intact
175 The complete text of this example is in F<examples/powers5> in the
176 distribution set (it is not installed as part of the module.
180 # ----------------------------------------------------------------------
182 # Pragmas --------------------------
186 # Inheritance ----------------------
188 use base qw( Exporter );
189 use vars '@EXPORT_OK';
190 @EXPORT_OK = qw( $PACKAGE $VERSION );
192 # Utility --------------------------
194 use Carp qw( croak );
195 use Class::MethodMaker 1.02 qw( );
196 use Fatal qw( open sysopen close seek );
197 use POSIX qw( ceil strftime );
199 # ----------------------------------------------------------------------
201 # CLASS METHODS --------------------------------------------------------
203 # ----------------------------------
205 # ----------------------------------
207 =head1 CLASS CONSTANTS
213 use constant MINUTE => 60;
214 use constant HOUR => 60 * MINUTE;
215 use constant DAY => 24 * HOUR;
217 # The point past which to give ETA of just date, rather than time
218 use constant ETA_DATE_CUTOFF => 3 * DAY;
219 # The point past which to give ETA of time, rather time left
220 use constant ETA_TIME_CUTOFF => 10 * MINUTE;
221 # The ratio prior to which to not dare any estimates
222 use constant PREDICT_RATIO => 0.01;
224 use constant DEFAULTS => {
232 max_update_rate => 0.5,
234 # The following defaults are never used, but the keys
235 # are valuable for error checking
243 use constant ETA_TYPES => { map { $_ => 1 } qw( linear ) };
245 use constant ALREADY_FINISHED => 'progress bar already finished';
247 use constant DEBUG => 0;
249 # -------------------------------------
251 use vars qw($PACKAGE $VERSION);
252 $PACKAGE = 'Term-ProgressBar';
255 # ----------------------------------
257 # ----------------------------------
259 # ----------------------------------
261 # ----------------------------------
263 # This is here to allow testing to redirect away from the terminal but still
264 # see terminal output, IYSWIM
265 my $__FORCE_TERM = 0;
267 # ----------------------------------
268 # CLASS HIGHER-LEVEL FUNCTIONS
269 # ----------------------------------
271 # ----------------------------------
272 # CLASS HIGHER-LEVEL PROCEDURES
273 # ----------------------------------
277 ($__FORCE_TERM) = @_;
280 # ----------------------------------
281 # CLASS UTILITY FUNCTIONS
282 # ----------------------------------
288 require Term::ReadKey;
290 warn "Guessing terminal width due to problem with Term::ReadKey\n";
296 $result = (Term::ReadKey::GetTerminalSize($fh))[0];
297 $result-- if ($^O eq "MSWin32");
299 warn "error from Term::ReadKey::GetTerminalSize(): $@";
302 # If GetTerminalSize() failed it should (according to its docs)
303 # return an empty list. It doesn't - that's why we have the eval {}
304 # above - but also it may appear to succeed and return a width of
309 warn "guessing terminal width $result\n";
316 # INSTANCE METHODS -----------------------------------------------------
318 # ----------------------------------
319 # INSTANCE CONSTRUCTION
320 # ----------------------------------
322 =head1 INSTANCE CONSTRUCTION
328 # Don't document hash keys until tested that the give the desired affect!
332 Create & return a new Term::ProgressBar instance.
338 If one argument is provided, and it is a hashref, then the hash is treated as
339 a set of key/value pairs, with the following keys; otherwise, it is treated as
340 a number, being equivalent to the C<count> key.
346 The item count. The progress is marked at 100% when update I<count> is
347 invoked, and proportionally until then.
351 A name to prefix the progress bar with.
355 The filehandle to output to. Defaults to stderr. Do not try to use
356 *foo{THING} syntax if you want Term capabilities; it does not work. Pass in a
361 A total time estimation to use. If enabled, a time finished estimation is
362 printed on the RHS (once sufficient updates have been performed to make such
363 an estimation feasible). Naturally, this is an I<estimate>; no guarantees are
364 made. The format of the estimate
366 Note that the format is intended to be as compact as possible while giving
367 over the relevant information. Depending upon the time remaining, the format
368 is selected to provide some resolution whilst remaining compact. Since the
369 time remaining decreases, the format typically changes over time.
371 As the ETA approaches, the format will state minutes & seconds left. This is
372 identifiable by the word C<'Left'> at the RHS of the line. If the ETA is
373 further away, then an estimate time of completion (rather than time left) is
374 given, and is identifiable by C<'ETA'> at the LHS of the ETA box (on the right
375 of the progress bar). A time or date may be presented; these are of the form
376 of a 24 hour clock, e.g. C<'13:33'>, a time plus days (e.g., C<' 7PM+3'> for
377 around in over 3 days time) or a day/date, e.g. C<' 1Jan'> or C<'27Feb'>.
379 If ETA is switched on, the return value of L<update|"update"> is also
380 affected: the idea here is that if the progress bar seems to be moving quicker
381 than the eye would normally care for (and thus a great deal of time is spent
382 doing progress updates rather than "real" work), the next value is increased
383 to slow it. The maximum rate aimed for is tunable via the
384 L<max_update_rate|"max_update_rate"> component.
386 The available values for this are:
392 Do not do estimation. The default.
396 Perform linear estimation. This is simply that the amount of time between the
397 creation of the progress bar and now is divided by the current amount done,
398 and completion estimated linearly.
406 my $progress = Term::ProgressBar->new(100); # count from 1 to 100
407 my $progress = Term::ProgressBar->new({ count => 100 }); # same
409 # Count to 200 thingies, outputting to stdout instead of stderr,
410 # prefix bar with 'thingy'
411 my $progress = Term::ProgressBar->new({ count => 200,
419 Class::MethodMaker->import (new_with_init => 'new',
420 new_hash_init => 'hash_init',);
426 return $self->init({count => $_[1], name => $_[0],
427 term_width => 50, bar_width => 50,
428 major_char => '#', minor_char => '',
429 lbrack => '', rbrack => '',
430 term => '0 but true', })
436 sprintf("Term::ProgressBar::new We don't handle this many arguments: %d",
442 if ( UNIVERSAL::isa ($_[0], 'HASH') ) {
443 ($target) = @{$_[0]}{qw(count)};
444 %config = %{$_[0]}; # Copy in, so later playing does not tinker externally
449 if ( my @bad = grep ! exists DEFAULTS->{$_}, keys %config ) {
450 croak sprintf("Input parameters (%s) to %s not recognized\n",
451 join(':', @bad), 'Term::ProgressBar::new');
454 croak "Target count required for Term::ProgressBar new\n"
455 unless defined $target;
457 $config{$_} = DEFAULTS->{$_}
458 for grep ! exists $config{$_}, keys %{DEFAULTS()};
459 delete $config{count};
461 $config{term} = -t $config{fh}
462 unless defined $config{term};
464 if ( $__FORCE_TERM ) {
466 $config{term_width} = $__FORCE_TERM;
467 die "term width $config{term_width} (from __force_term) too small"
468 if $config{term_width} < 5;
469 } elsif ( $config{term} and ! defined $config{term_width}) {
470 $config{term_width} = term_size($config{fh});
471 die if $config{term_width} < 5;
474 unless ( defined $config{bar_width} ) {
475 if ( defined $config{term_width} ) {
477 $config{bar_width} = $config{term_width} - 5;
478 $config{bar_width} -= $_
479 for map(( defined $config{$_} ? length($config{$_}) : 0),
480 qw( lbrack rbrack name ));
481 $config{bar_width} -= 2 # Extra for ': '
482 if defined $config{name};
483 $config{bar_width} -= 10
484 if defined $config{ETA};
485 if ( $config{bar_width} < 1 ) {
486 warn "terminal width $config{term_width} too small for bar; defaulting to 10\n";
487 $config{bar_width} = 10;
489 # } elsif ( ! $config{term} ) {
490 # $config{bar_width} = 1;
491 # $config{term_width} = defined $config{ETA} ? 12 : 5;
493 $config{bar_width} = $target;
494 die "configured bar_width $config{bar_width} < 1"
495 if $config{bar_width} < 1;
499 $config{start} = time;
501 select(((select $config{fh}), $| = 1)[0]);
503 $self->ETA(delete $config{ETA});
505 $self->hash_init (%config,
513 $self->target($target);
514 $self->minor($config{term} && $target > $config{bar_width} ** 1.5);
516 $self->update(0); # Initialize the progress bar
520 # ----------------------------------
521 # INSTANCE FINALIZATION
522 # ----------------------------------
524 # ----------------------------------
525 # INSTANCE COMPONENTS
526 # ----------------------------------
528 =head1 INSTANCE COMPONENTS
532 =head2 Scalar Components.
534 See L<Class::MethodMaker/get_set> for usage.
540 The final target. Updates are measured in terms of this. Changes will have
541 no effect until the next update, but the next update value should be relative
542 to the new target. So
544 $p = Term::ProgressBar({count => 20});
551 will cause the progress bar to update to 52.5%
553 =item max_update_rate
555 This value is taken as being the maximum speed between updates to aim for.
556 B<It is only meaningful if ETA is switched on.> It defaults to 0.5, being the
557 number of seconds between updates.
561 =head2 Boolean Components
563 See L<Class::MethodMaker/get_set> for usage.
569 Default: set. If unset, no minor scale will be calculated or updated.
571 Minor characters are used on the progress bar to give the user the idea of
572 progress even when there are so many more tasks than the terminal is wide that
573 the granularity would be too great. By default, Term::ProgressBar makes a
574 guess as to when minor characters would be valuable. However, it may not
575 always guess right, so this method may be called to force it one way or the
576 other. Of course, the efficiency saving is minimal unless the client is
577 utilizing the return value of L<update|"update">.
579 See F<examples/powers4> and F<examples/powers3> to see minor characters in
580 action, and not in action, respectively.
586 # Private Scalar Components
587 # offset ) Default: 0. Added to any value supplied to update.
588 # scale ) Default: 1. Any value supplied to update is multiplied by
590 # major_char) Default: '='. The character printed for the major scale.
591 # minor_char) Default: '*'. The character printed for the minor scale.
592 # name ) Default: undef. The name to print to the side of the bar.
593 # fh ) Default: STDERR. The filehandle to output progress to.
595 # Private Counter Components
596 # last_update ) Default: 0. The so_far value last time update was invoked.
597 # last_position) Default: 0. The number of the last progress mark printed.
599 # Private Boolean Components
600 # term ) Default: detected (by C<Term::ReadKey>).
601 # If unset, we assume that we are not connected to a terminal (or
602 # at least, not a suitably intelligent one). Then, we attempt
603 # minimal functionality.
605 Class::MethodMaker->import
607 get_set => [qw/ major_units major_char
608 minor_units minor_char
615 counter => [qw/ last_position last_update /],
616 boolean => [qw/ minor name_printed pb_ended remove /],
617 # let it be boolean to handle 0 but true
618 get_set => [qw/ term /],
621 # We generate these by hand since we want to check the values.
624 return $self->{bar_width} if not @_;
625 croak 'wrong number of arguments' if @_ != 1;
626 croak 'bar_width < 1' if $_[0] < 1;
627 $self->{bar_width} = $_[0];
631 return $self->{term_width} if not @_;
632 croak 'wrong number of arguments' if @_ != 1;
633 croak 'term_width must be at least 5' if $self->term and $_[0] < 5;
634 $self->{term_width} = $_[0];
644 $self->major_units($self->bar_width / $target);
645 $self->minor_units($self->bar_width ** 2 / $target);
646 $self->minor ( defined $self->term_width and
647 $self->term_width < $target );
649 $self->{target} = $target;
652 return $self->{target};
660 croak "Invalid ETA type: $type\n"
661 if defined $type and ! exists ETA_TYPES->{$type};
662 $self->{ETA} = $type;
668 # ----------------------------------
669 # INSTANCE HIGHER-LEVEL FUNCTIONS
670 # ----------------------------------
672 # ----------------------------------
673 # INSTANCE HIGHER-LEVEL PROCEDURES
674 # ----------------------------------
676 =head1 INSTANCE HIGHER-LEVEL PROCEDURES
683 warn sprintf("%s: This method is deprecated. Please use %s instead\n",
684 (caller (0))[3], '$x->minor (0)',);
685 $_[0]->clear_minor (0);
688 # -------------------------------------
692 Update the progress bar.
702 Current progress point, in whatever units were passed to C<new>.
704 If not defined, assumed to be 1+ whatever was the value last time C<update>
705 was called (starting at 0).
715 The next value of so_far at which to call C<update>.
727 if ( ! defined $so_far ) {
728 $so_far = $self->last_update + 1;
731 my $input_so_far = $so_far;
732 $so_far *= $self->scale
733 unless $self->scale == 1;
734 $so_far += $self->offset;
736 my $target = my $next = $self->target;
737 my $name = $self->name;
744 print $fh "(nothing to do)\n";
748 my $biggies = $self->major_units * $so_far;
749 my @chars = (' ') x $self->bar_width;
750 $chars[$_] = $self->major_char
753 if ( $self->minor ) {
754 my $smally = $self->minor_units * $so_far % $self->bar_width;
755 $chars[$smally] = $self->minor_char
756 unless $so_far == $target;
757 $next *= ($self->minor_units * $so_far + 1) / ($self->bar_width ** 2);
759 $next *= ($self->major_units * $so_far + 1) / $self->bar_width;
764 if ( $self->term > 0 ) {
767 $to_print .= "$name: "
769 my $ratio = $so_far / $target;
771 $to_print .= (sprintf ("%3d%% %s%s%s",
773 $self->lbrack, join ('', @chars), $self->rbrack));
774 my $ETA = $self->ETA;
775 if ( defined $ETA and $ratio > 0 ) {
776 if ( $ETA eq 'linear' ) {
778 my $taken = time - $self->start;
779 my $ss = $taken % 60;
780 my $mm = int(($taken % 3600) / 60);
781 my $hh = int($taken / 3600);
783 $to_print .= sprintf('D %2dh%02dm', $hh, $mm, $ss);
785 $to_print .= sprintf('D%2dh%02dm%02ds', $hh, $mm, $ss);
787 } elsif ( $ratio < PREDICT_RATIO ) {
788 # No safe prediction yet
789 $to_print .= 'ETA ------';
792 my $left = (($time - $self->start) * ((1 - $ratio) / $ratio));
793 if ( $left < ETA_TIME_CUTOFF ) {
794 $to_print .= sprintf '%1dm%02ds Left', int($left / 60), $left % 60;
796 my $eta = $time + $left;
799 $format = 'ETA %H:%M';
800 } elsif ( $left < ETA_DATE_CUTOFF ) {
801 $format = sprintf('ETA %%l%%p+%d',$left/DAY);
803 $format = 'ETA %e%b';
805 $to_print .= strftime($format, localtime $eta);
807 # Calculate next to be at least SEC_PER_UPDATE seconds away
809 my $incr = ($target - $so_far) / ($left / $self->max_update_rate);
810 $next = $so_far + $incr
811 if $so_far + $incr > $next;
815 croak "Bad ETA type: $ETA\n";
818 for ($self->{last_printed}) {
819 unless (defined and $_ eq $to_print) {
825 $next -= $self->offset;
826 $next /= $self->scale
827 unless $self->scale == 1;
829 if ( $so_far >= $target and $self->remove and ! $self->pb_ended) {
830 print $fh "\r", ' ' x $self->term_width, "\r";
837 if ( $self->term ) { # special case for backwards compat.
838 if ( $so_far == 0 and defined $name and ! $self->name_printed ) {
840 $self->set_name_printed;
843 my $position = int($self->bar_width * ($input_so_far / $target));
844 my $add = $position - $self->last_position;
845 $self->last_position_incr ($add)
848 print $fh $self->major_char x $add;
850 $next -= $self->offset;
851 $next /= $self->scale
852 unless $self->scale == 1;
854 my $pc = int(100*$input_so_far/$target);
855 printf $fh "[%s] %s: %3d%%\n", scalar(localtime), $name, $pc;
857 $next = ceil($target * ($pc+1)/100);
860 if ( $input_so_far >= $target ) {
861 if ( $self->pb_ended ) {
862 croak ALREADY_FINISHED;
873 $next = $target if $next > $target;
875 $self->last_update($input_so_far);
879 # -------------------------------------
883 Output a message. This is very much like print, but we try not to disturb the
894 The message to output.
910 print $fh "\r", ' ' x $self->term_width;
911 print $fh "\r$string\n";
913 print $fh "\n$string\n";
914 print $fh $self->major_char x $self->last_position;
916 undef $self->{last_printed};
917 $self->update($self->last_update);
921 # ----------------------------------------------------------------------
927 =head1 REPORTING BUGS
933 If exactly two arguments are provided, then L<new|"new"> operates in v1
934 compatibility mode: the arguments are considered to be name, and item count.
935 Various other defaults are set to emulate version one (e.g., the major output
936 character is '#', the bar width is set to 50 characters and the output
937 filehandle is not treated as a terminal). This mode is deprecated.
941 Martyn J. Pearce fluffy@cpan.org
943 Significant contributions from Ed Avis, amongst others.
947 Copyright (c) 2001, 2002, 2003, 2004, 2005 Martyn J. Pearce. This program is
948 free software; you can redistribute it and/or modify it under the same terms
957 1; # keep require happy.