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($_);
80 Here is a simple example. The process considers all the numbers between 0 and
81 MAX, and updates the progress bar whenever it finds one. Note that the
82 progress bar update will be very erratic. See below for a smoother example.
83 Note also that the progress bar will never complete; see below to solve this.
85 The complete text of this example is in F<examples/powers> in the
86 distribution set (it is not installed as part of the module).
88 =head2 A smoother bar update
90 my $progress = Term::ProgressBar->new($max);
94 for(my $i = 0; 2**$i <= $_; $i++) {
104 This example calls update for each value considered. This will result in a
105 much smoother progress update, but more program time is spent updating the bar
106 than doing the "real" work. See below to remedy this. This example does
107 I<not> call C<< $progress->update($max); >> at the end, since it is
108 unnecessary, and ProgressBar will throw an exception at an attempt to update a
111 The complete text of this example is in F<examples/powers2> in the
112 distribution set (it is not installed as part of the module.
114 =head2 A (much) more efficient update
116 my $progress = Term::ProgressBar->new({name => 'Powers', count => $max, remove => 1});
122 for(my $i = 0; 2**$i <= $_; $i++) {
127 $next_update = $progress->update($_)
128 if $_ >= $next_update;
130 $progress->update($max)
131 if $max >= $next_update;
133 This example does two things to improve efficiency: firstly, it uses the value
134 returned by L<update|"update"> to only call it again when needed; secondly, it
135 switches off the use of minor characters to update a lot less frequently (C<<
136 $progress->minor(0); >>. The use of the return value of L<update|"update">
137 means that the call of C<< $progress->update($max); >> at the end is required
138 to ensure that the bar ends on 100%, which gives the user a nice feeling.
140 This example also sets the name of the progress bar.
142 This example also demonstrates the use of the 'remove' flag, which removes the
143 progress bar from the terminal when done.
145 The complete text of this example is in F<examples/powers3> in the
146 distribution set (it is not installed as part of the module.
148 =head2 Using Completion Time Estimation
150 my $progress = Term::ProgressBar->new({name => 'Powers',
153 $progress->max_update_rate(1);
158 for(my $i = 0; 2**$i <= $_; $i++) {
161 $progress->message(sprintf "Found %8d to be 2 ** %2d", $_, $i);
165 $next_update = $progress->update($_)
166 if $_ > $next_update;
168 $progress->update($max)
169 if $max >= $next_update;
171 This example uses the L<ETA|"ETA"> option to switch on completion estimation.
172 Also, the update return is tuned to try to update the bar approximately once
173 per second, with the L<max_update_rate|"max_update_rate"> call. See the
174 documentation for the L<new|new> method for details of the format(s) used.
176 This example also provides an example of the use of the L<message|"message">
177 function to output messages to the same filehandle whilst keeping the progress bar intact
179 The complete text of this example is in F<examples/powers5> in the
180 distribution set (it is not installed as part of the module.
184 # ----------------------------------------------------------------------
186 # Pragmas --------------------------
190 # Inheritance ----------------------
192 use base qw( Exporter );
193 use vars '@EXPORT_OK';
194 @EXPORT_OK = qw( $PACKAGE $VERSION );
196 # Utility --------------------------
198 use Carp qw( croak );
199 use Class::MethodMaker 1.02 qw( );
200 use Fatal qw( open sysopen close seek );
201 use POSIX qw( ceil strftime );
203 # ----------------------------------------------------------------------
205 # CLASS METHODS --------------------------------------------------------
207 # ----------------------------------
209 # ----------------------------------
211 =head1 CLASS CONSTANTS
217 use constant MINUTE => 60;
218 use constant HOUR => 60 * MINUTE;
219 use constant DAY => 24 * HOUR;
221 # The point past which to give ETA of just date, rather than time
222 use constant ETA_DATE_CUTOFF => 3 * DAY;
223 # The point past which to give ETA of time, rather time left
224 use constant ETA_TIME_CUTOFF => 10 * MINUTE;
225 # The ratio prior to which to not dare any estimates
226 use constant PREDICT_RATIO => 0.01;
228 use constant DEFAULTS => {
236 max_update_rate => 0.5,
238 # The following defaults are never used, but the keys
239 # are valuable for error checking
247 use constant ETA_TYPES => { map { $_ => 1 } qw( linear ) };
249 use constant ALREADY_FINISHED => 'progress bar already finished';
251 use constant DEBUG => 0;
253 # -------------------------------------
255 use vars qw($PACKAGE $VERSION);
256 $PACKAGE = 'Term-ProgressBar';
259 # ----------------------------------
261 # ----------------------------------
263 # ----------------------------------
265 # ----------------------------------
267 # This is here to allow testing to redirect away from the terminal but still
268 # see terminal output, IYSWIM
269 my $__FORCE_TERM = 0;
271 # ----------------------------------
272 # CLASS HIGHER-LEVEL FUNCTIONS
273 # ----------------------------------
275 # ----------------------------------
276 # CLASS HIGHER-LEVEL PROCEDURES
277 # ----------------------------------
281 ($__FORCE_TERM) = @_;
284 # ----------------------------------
285 # CLASS UTILITY FUNCTIONS
286 # ----------------------------------
292 require Term::ReadKey;
294 warn "Guessing terminal width due to problem with Term::ReadKey\n";
300 $result = (Term::ReadKey::GetTerminalSize($fh))[0];
301 $result-- if ($^O eq "MSWin32");
303 warn "error from Term::ReadKey::GetTerminalSize(): $@";
306 # If GetTerminalSize() failed it should (according to its docs)
307 # return an empty list. It doesn't - that's why we have the eval {}
308 # above - but also it may appear to succeed and return a width of
313 warn "guessing terminal width $result\n";
320 # INSTANCE METHODS -----------------------------------------------------
322 # ----------------------------------
323 # INSTANCE CONSTRUCTION
324 # ----------------------------------
326 =head1 INSTANCE CONSTRUCTION
332 # Don't document hash keys until tested that the give the desired affect!
336 Create & return a new Term::ProgressBar instance.
342 If one argument is provided, and it is a hashref, then the hash is treated as
343 a set of key/value pairs, with the following keys; otherwise, it is treated as
344 a number, being equivalent to the C<count> key.
350 The item count. The progress is marked at 100% when update I<count> is
351 invoked, and proportionally until then.
355 A name to prefix the progress bar with.
359 The filehandle to output to. Defaults to stderr. Do not try to use
360 *foo{THING} syntax if you want Term capabilities; it does not work. Pass in a
365 A total time estimation to use. If enabled, a time finished estimation is
366 printed on the RHS (once sufficient updates have been performed to make such
367 an estimation feasible). Naturally, this is an I<estimate>; no guarantees are
368 made. The format of the estimate
370 Note that the format is intended to be as compact as possible while giving
371 over the relevant information. Depending upon the time remaining, the format
372 is selected to provide some resolution whilst remaining compact. Since the
373 time remaining decreases, the format typically changes over time.
375 As the ETA approaches, the format will state minutes & seconds left. This is
376 identifiable by the word C<'Left'> at the RHS of the line. If the ETA is
377 further away, then an estimate time of completion (rather than time left) is
378 given, and is identifiable by C<'ETA'> at the LHS of the ETA box (on the right
379 of the progress bar). A time or date may be presented; these are of the form
380 of a 24 hour clock, e.g. C<'13:33'>, a time plus days (e.g., C<' 7PM+3'> for
381 around in over 3 days time) or a day/date, e.g. C<' 1Jan'> or C<'27Feb'>.
383 If ETA is switched on, the return value of L<update|"update"> is also
384 affected: the idea here is that if the progress bar seems to be moving quicker
385 than the eye would normally care for (and thus a great deal of time is spent
386 doing progress updates rather than "real" work), the next value is increased
387 to slow it. The maximum rate aimed for is tunable via the
388 L<max_update_rate|"max_update_rate"> component.
390 The available values for this are:
396 Do not do estimation. The default.
400 Perform linear estimation. This is simply that the amount of time between the
401 creation of the progress bar and now is divided by the current amount done,
402 and completion estimated linearly.
410 my $progress = Term::ProgressBar->new(100); # count from 1 to 100
411 my $progress = Term::ProgressBar->new({ count => 100 }); # same
413 # Count to 200 thingies, outputting to stdout instead of stderr,
414 # prefix bar with 'thingy'
415 my $progress = Term::ProgressBar->new({ count => 200,
423 Class::MethodMaker->import (new_with_init => 'new',
424 new_hash_init => 'hash_init',);
430 return $self->init({count => $_[1], name => $_[0],
431 term_width => 50, bar_width => 50,
432 major_char => '#', minor_char => '',
433 lbrack => '', rbrack => '',
434 term => '0 but true', })
440 sprintf("Term::ProgressBar::new We don't handle this many arguments: %d",
446 if ( UNIVERSAL::isa ($_[0], 'HASH') ) {
447 ($target) = @{$_[0]}{qw(count)};
448 %config = %{$_[0]}; # Copy in, so later playing does not tinker externally
453 if ( my @bad = grep ! exists DEFAULTS->{$_}, keys %config ) {
454 croak sprintf("Input parameters (%s) to %s not recognized\n",
455 join(':', @bad), 'Term::ProgressBar::new');
458 croak "Target count required for Term::ProgressBar new\n"
459 unless defined $target;
461 $config{$_} = DEFAULTS->{$_}
462 for grep ! exists $config{$_}, keys %{DEFAULTS()};
463 delete $config{count};
465 $config{term} = -t $config{fh}
466 unless defined $config{term};
468 if ( $__FORCE_TERM ) {
470 $config{term_width} = $__FORCE_TERM;
471 die "term width $config{term_width} (from __force_term) too small"
472 if $config{term_width} < 5;
473 } elsif ( $config{term} and ! defined $config{term_width}) {
474 $config{term_width} = term_size($config{fh});
475 die if $config{term_width} < 5;
478 unless ( defined $config{bar_width} ) {
479 if ( defined $config{term_width} ) {
481 $config{bar_width} = $config{term_width} - 5;
482 $config{bar_width} -= $_
483 for map(( defined $config{$_} ? length($config{$_}) : 0),
484 qw( lbrack rbrack name ));
485 $config{bar_width} -= 2 # Extra for ': '
486 if defined $config{name};
487 $config{bar_width} -= 10
488 if defined $config{ETA};
489 if ( $config{bar_width} < 1 ) {
490 warn "terminal width $config{term_width} too small for bar; defaulting to 10\n";
491 $config{bar_width} = 10;
493 # } elsif ( ! $config{term} ) {
494 # $config{bar_width} = 1;
495 # $config{term_width} = defined $config{ETA} ? 12 : 5;
497 $config{bar_width} = $target;
498 die "configured bar_width $config{bar_width} < 1"
499 if $config{bar_width} < 1;
503 $config{start} = time;
505 select(((select $config{fh}), $| = 1)[0]);
507 $self->ETA(delete $config{ETA});
509 $self->hash_init (%config,
517 $self->target($target);
518 $self->minor($config{term} && $target > $config{bar_width} ** 1.5);
520 $self->update(0); # Initialize the progress bar
524 # ----------------------------------
525 # INSTANCE FINALIZATION
526 # ----------------------------------
528 # ----------------------------------
529 # INSTANCE COMPONENTS
530 # ----------------------------------
532 =head1 INSTANCE COMPONENTS
536 =head2 Scalar Components.
538 See L<Class::MethodMaker/get_set> for usage.
544 The final target. Updates are measured in terms of this. Changes will have
545 no effect until the next update, but the next update value should be relative
546 to the new target. So
548 $p = Term::ProgressBar({count => 20});
555 will cause the progress bar to update to 52.5%
557 =item max_update_rate
559 This value is taken as being the maximum speed between updates to aim for.
560 B<It is only meaningful if ETA is switched on.> It defaults to 0.5, being the
561 number of seconds between updates.
565 =head2 Boolean Components
567 See L<Class::MethodMaker/get_set> for usage.
573 Default: set. If unset, no minor scale will be calculated or updated.
575 Minor characters are used on the progress bar to give the user the idea of
576 progress even when there are so many more tasks than the terminal is wide that
577 the granularity would be too great. By default, Term::ProgressBar makes a
578 guess as to when minor characters would be valuable. However, it may not
579 always guess right, so this method may be called to force it one way or the
580 other. Of course, the efficiency saving is minimal unless the client is
581 utilizing the return value of L<update|"update">.
583 See F<examples/powers4> and F<examples/powers3> to see minor characters in
584 action, and not in action, respectively.
590 # Private Scalar Components
591 # offset ) Default: 0. Added to any value supplied to update.
592 # scale ) Default: 1. Any value supplied to update is multiplied by
594 # major_char) Default: '='. The character printed for the major scale.
595 # minor_char) Default: '*'. The character printed for the minor scale.
596 # name ) Default: undef. The name to print to the side of the bar.
597 # fh ) Default: STDERR. The filehandle to output progress to.
599 # Private Counter Components
600 # last_update ) Default: 0. The so_far value last time update was invoked.
601 # last_position) Default: 0. The number of the last progress mark printed.
603 # Private Boolean Components
604 # term ) Default: detected (by C<Term::ReadKey>).
605 # If unset, we assume that we are not connected to a terminal (or
606 # at least, not a suitably intelligent one). Then, we attempt
607 # minimal functionality.
609 Class::MethodMaker->import
611 get_set => [qw/ major_units major_char
612 minor_units minor_char
619 counter => [qw/ last_position last_update /],
620 boolean => [qw/ minor name_printed pb_ended remove /],
621 # let it be boolean to handle 0 but true
622 get_set => [qw/ term /],
625 # We generate these by hand since we want to check the values.
628 return $self->{bar_width} if not @_;
629 croak 'wrong number of arguments' if @_ != 1;
630 croak 'bar_width < 1' if $_[0] < 1;
631 $self->{bar_width} = $_[0];
635 return $self->{term_width} if not @_;
636 croak 'wrong number of arguments' if @_ != 1;
637 croak 'term_width must be at least 5' if $self->term and $_[0] < 5;
638 $self->{term_width} = $_[0];
648 $self->major_units($self->bar_width / $target);
649 $self->minor_units($self->bar_width ** 2 / $target);
650 $self->minor ( defined $self->term_width and
651 $self->term_width < $target );
653 $self->{target} = $target;
656 return $self->{target};
664 croak "Invalid ETA type: $type\n"
665 if defined $type and ! exists ETA_TYPES->{$type};
666 $self->{ETA} = $type;
672 # ----------------------------------
673 # INSTANCE HIGHER-LEVEL FUNCTIONS
674 # ----------------------------------
676 # ----------------------------------
677 # INSTANCE HIGHER-LEVEL PROCEDURES
678 # ----------------------------------
680 =head1 INSTANCE HIGHER-LEVEL PROCEDURES
687 warn sprintf("%s: This method is deprecated. Please use %s instead\n",
688 (caller (0))[3], '$x->minor (0)',);
689 $_[0]->clear_minor (0);
692 # -------------------------------------
696 Update the progress bar.
706 Current progress point, in whatever units were passed to C<new>.
708 If not defined, assumed to be 1+ whatever was the value last time C<update>
709 was called (starting at 0).
719 The next value of so_far at which to call C<update>.
731 if ( ! defined $so_far ) {
732 $so_far = $self->last_update + 1;
735 my $input_so_far = $so_far;
736 $so_far *= $self->scale
737 unless $self->scale == 1;
738 $so_far += $self->offset;
740 my $target = my $next = $self->target;
741 my $name = $self->name;
748 print $fh "(nothing to do)\n";
752 my $biggies = $self->major_units * $so_far;
753 my @chars = (' ') x $self->bar_width;
754 $chars[$_] = $self->major_char
757 if ( $self->minor ) {
758 my $smally = $self->minor_units * $so_far % $self->bar_width;
759 $chars[$smally] = $self->minor_char
760 unless $so_far == $target;
761 $next *= ($self->minor_units * $so_far + 1) / ($self->bar_width ** 2);
763 $next *= ($self->major_units * $so_far + 1) / $self->bar_width;
768 if ( $self->term > 0 ) {
771 $to_print .= "$name: "
773 my $ratio = $so_far / $target;
775 $to_print .= (sprintf ("%3d%% %s%s%s",
777 $self->lbrack, join ('', @chars), $self->rbrack));
778 my $ETA = $self->ETA;
779 if ( defined $ETA and $ratio > 0 ) {
780 if ( $ETA eq 'linear' ) {
782 my $taken = time - $self->start;
783 my $ss = $taken % 60;
784 my $mm = int(($taken % 3600) / 60);
785 my $hh = int($taken / 3600);
787 $to_print .= sprintf('D %2dh%02dm', $hh, $mm, $ss);
789 $to_print .= sprintf('D%2dh%02dm%02ds', $hh, $mm, $ss);
791 } elsif ( $ratio < PREDICT_RATIO ) {
792 # No safe prediction yet
793 $to_print .= 'ETA ------';
796 my $left = (($time - $self->start) * ((1 - $ratio) / $ratio));
797 if ( $left < ETA_TIME_CUTOFF ) {
798 $to_print .= sprintf '%1dm%02ds Left', int($left / 60), $left % 60;
800 my $eta = $time + $left;
803 $format = 'ETA %H:%M';
804 } elsif ( $left < ETA_DATE_CUTOFF ) {
805 $format = sprintf('ETA %%l%%p+%d',$left/DAY);
807 $format = 'ETA %e%b';
809 $to_print .= strftime($format, localtime $eta);
811 # Calculate next to be at least SEC_PER_UPDATE seconds away
813 my $incr = ($target - $so_far) / ($left / $self->max_update_rate);
814 $next = $so_far + $incr
815 if $so_far + $incr > $next;
819 croak "Bad ETA type: $ETA\n";
822 for ($self->{last_printed}) {
823 unless (defined and $_ eq $to_print) {
829 $next -= $self->offset;
830 $next /= $self->scale
831 unless $self->scale == 1;
833 if ( $so_far >= $target and $self->remove and ! $self->pb_ended) {
834 print $fh "\r", ' ' x $self->term_width, "\r";
841 if ( $self->term ) { # special case for backwards compat.
842 if ( $so_far == 0 and defined $name and ! $self->name_printed ) {
844 $self->set_name_printed;
847 my $position = int($self->bar_width * ($input_so_far / $target));
848 my $add = $position - $self->last_position;
849 $self->last_position_incr ($add)
852 print $fh $self->major_char x $add;
854 $next -= $self->offset;
855 $next /= $self->scale
856 unless $self->scale == 1;
858 my $pc = int(100*$input_so_far/$target);
859 printf $fh "[%s] %s: %3d%%\n", scalar(localtime), $name, $pc;
861 $next = ceil($target * ($pc+1)/100);
864 if ( $input_so_far >= $target ) {
865 if ( $self->pb_ended ) {
866 croak ALREADY_FINISHED;
877 $next = $target if $next > $target;
879 $self->last_update($input_so_far);
883 # -------------------------------------
887 Output a message. This is very much like print, but we try not to disturb the
898 The message to output.
914 print $fh "\r", ' ' x $self->term_width;
915 print $fh "\r$string\n";
917 print $fh "\n$string\n";
918 print $fh $self->major_char x $self->last_position;
920 undef $self->{last_printed};
921 $self->update($self->last_update);
925 # ----------------------------------------------------------------------
931 =head1 REPORTING BUGS
937 If exactly two arguments are provided, then L<new|"new"> operates in v1
938 compatibility mode: the arguments are considered to be name, and item count.
939 Various other defaults are set to emulate version one (e.g., the major output
940 character is '#', the bar width is set to 50 characters and the output
941 filehandle is not treated as a terminal). This mode is deprecated.
945 Martyn J. Pearce fluffy@cpan.org
947 Significant contributions from Ed Avis, amongst others.
951 Copyright (c) 2001, 2002, 2003, 2004, 2005 Martyn J. Pearce. This program is
952 free software; you can redistribute it and/or modify it under the same terms
961 1; # keep require happy.