]> git.donarmstrong.com Git - term-progressbar.git/blob - lib/Term/ProgressBar.pm
v2.12
[term-progressbar.git] / lib / Term / ProgressBar.pm
1 # (X)Emacs mode: -*- cperl -*-
2
3 package Term::ProgressBar;
4
5 #XXX TODO Redo original test with count=20
6 #         Amount Output
7 #         Amount Prefix/Suffix
8 #         Tinker with $0?
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?
15
16 =head1  NAME
17
18 Term::ProgressBar - provide a progress meter on a standard terminal
19
20 =head1  SYNOPSIS
21
22   use Term::ProgressBar;
23
24   $progress = Term::ProgressBar->new ({count => $count});
25   $progress->update ($so_far);
26
27 =head1  DESCRIPTION
28
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.
32
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.
35
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.
41
42 Remember to call the C<< $progress->update($max_value) >> when the job is done
43 to get a nice 100% done bar.
44
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.
53
54 =head1 EXAMPLES
55
56 =head2 A really simple use
57
58   #!/usr/bin/perl
59
60   use Term::ProgressBar 2.00;
61
62   use constant MAX => 100_000;
63
64   my $progress = Term::ProgressBar->new(MAX);
65
66   for (0..MAX) {
67     my $is_power = 0;
68     for(my $i = 0; 2**$i <= $_; $i++) {
69       $is_power = 1
70         if 2**$i == $_;
71     }
72
73     if ( $is_power ) {
74       $progress->update($_);
75     }
76   }
77
78 see eg/simle_use.pl
79
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.
84
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).
87
88 =head2 A smoother bar update
89
90   my $progress = Term::ProgressBar->new($max);
91
92   for (0..$max) {
93     my $is_power = 0;
94     for(my $i = 0; 2**$i <= $_; $i++) {
95       $is_power = 1
96         if 2**$i == $_;
97     }
98
99     $progress->update($_)
100   }
101
102 See eg/smooth_bar.pl
103
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
109 finished bar.
110
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.
113
114 =head2 A (much) more efficient update
115
116   my $progress = Term::ProgressBar->new({name => 'Powers', count => $max, remove => 1});
117   $progress->minor(0);
118   my $next_update = 0;
119
120   for (0..$max) {
121     my $is_power = 0;
122     for(my $i = 0; 2**$i <= $_; $i++) {
123       $is_power = 1
124         if 2**$i == $_;
125     }
126
127     $next_update = $progress->update($_)
128       if $_ >= $next_update;
129   }
130   $progress->update($max)
131     if $max >= $next_update;
132
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.
139
140 This example also sets the name of the progress bar.
141
142 This example also demonstrates the use of the 'remove' flag, which removes the
143 progress bar from the terminal when done.
144
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.
147
148 =head2 Using Completion Time Estimation
149
150   my $progress = Term::ProgressBar->new({name  => 'Powers',
151                                          count => $max,
152                                          ETA   => 'linear', });
153   $progress->max_update_rate(1);
154   my $next_update = 0;
155
156   for (0..$max) {
157     my $is_power = 0;
158     for(my $i = 0; 2**$i <= $_; $i++) {
159       if ( 2**$i == $_ ) {
160         $is_power = 1;
161         $progress->message(sprintf "Found %8d to be 2 ** %2d", $_, $i);
162       }
163     }
164
165     $next_update = $progress->update($_)
166       if $_ > $next_update;
167   }
168   $progress->update($max)
169       if $max >= $next_update;
170
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.
175
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
178
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.
181
182 =cut
183
184 # ----------------------------------------------------------------------
185
186 # Pragmas --------------------------
187
188 use strict;
189
190 # Inheritance ----------------------
191
192 use base qw( Exporter );
193 use vars '@EXPORT_OK';
194 @EXPORT_OK = qw( $PACKAGE $VERSION );
195
196 # Utility --------------------------
197
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 );
202
203 # ----------------------------------------------------------------------
204
205 # CLASS METHODS --------------------------------------------------------
206
207 # ----------------------------------
208 # CLASS CONSTANTS
209 # ----------------------------------
210
211 =head1 CLASS CONSTANTS
212
213 Z<>
214
215 =cut
216
217 use constant MINUTE => 60;
218 use constant HOUR   => 60 * MINUTE;
219 use constant DAY    => 24 * HOUR;
220
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;
227
228 use constant DEFAULTS => {
229                           lbrack     => '[',
230                           rbrack     => ']',
231                           minor_char => '*',
232                           major_char => '=',
233                           fh         => \*STDERR,
234                           name       => undef,
235                           ETA        => undef,
236                           max_update_rate => 0.5,
237
238                           # The following defaults are never used, but the keys
239                           # are valuable for error checking
240                           count      => undef,
241                           bar_width  => undef,
242                           term_width => undef,
243                           term       => undef,
244                           remove     => 0,
245                          };
246
247 use constant ETA_TYPES => { map { $_ => 1 } qw( linear ) };
248
249 use constant ALREADY_FINISHED => 'progress bar already finished';
250
251 use constant DEBUG => 0;
252
253 # -------------------------------------
254
255 use vars qw($PACKAGE $VERSION);
256 $PACKAGE = 'Term-ProgressBar';
257 $VERSION = '2.12';
258
259 # ----------------------------------
260 # CLASS CONSTRUCTION
261 # ----------------------------------
262
263 # ----------------------------------
264 # CLASS COMPONENTS
265 # ----------------------------------
266
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;
270
271 # ----------------------------------
272 # CLASS HIGHER-LEVEL FUNCTIONS
273 # ----------------------------------
274
275 # ----------------------------------
276 # CLASS HIGHER-LEVEL PROCEDURES
277 # ----------------------------------
278
279 sub __force_term {
280   my $class = shift;
281   ($__FORCE_TERM) = @_;
282 }
283
284 # ----------------------------------
285 # CLASS UTILITY FUNCTIONS
286 # ----------------------------------
287
288 sub term_size {
289   my ($fh) = @_;
290
291   eval {
292     require Term::ReadKey;
293   }; if ($@) {
294     warn "Guessing terminal width due to problem with Term::ReadKey\n";
295     return 50;
296   }
297
298   my $result;
299   eval {
300     $result = (Term::ReadKey::GetTerminalSize($fh))[0];
301     $result-- if ($^O eq "MSWin32");
302   }; if ( $@ ) {
303     warn "error from Term::ReadKey::GetTerminalSize(): $@";
304   }
305
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
309   # zero.
310   #
311   if ( ! $result ) {
312     $result = 50;
313     warn "guessing terminal width $result\n";
314   }
315
316   return $result;
317 }
318
319
320 # INSTANCE METHODS -----------------------------------------------------
321
322 # ----------------------------------
323 # INSTANCE CONSTRUCTION
324 # ----------------------------------
325
326 =head1 INSTANCE CONSTRUCTION
327
328 Z<>
329
330 =cut
331
332 # Don't document hash keys until tested that the give the desired affect!
333
334 =head2 new
335
336 Create & return a new Term::ProgressBar instance.
337
338 =over 4
339
340 =item ARGUMENTS
341
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.
345
346 =over 4
347
348 =item count
349
350 The item count.  The progress is marked at 100% when update I<count> is
351 invoked, and proportionally until then.
352
353 =item name
354
355 A name to prefix the progress bar with.
356
357 =item fh
358
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
361 globref instead.
362
363 =item ETA
364
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
369
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.
374
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'>.
382
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.
389
390 The available values for this are:
391
392 =over 4
393
394 =item undef
395
396 Do not do estimation.  The default.
397
398 =item linear
399
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.
403
404 =back
405
406 =back
407
408 =item EXAMPLES
409
410   my $progress = Term::ProgressBar->new(100); # count from 1 to 100
411   my $progress = Term::ProgressBar->new({ count => 100 }); # same
412
413   # Count to 200 thingies, outputting to stdout instead of stderr,
414   # prefix bar with 'thingy'
415   my $progress = Term::ProgressBar->new({ count => 200,
416                                           fh    => \*STDOUT,
417                                           name  => 'thingy' });
418
419 =back
420
421 =cut
422
423 Class::MethodMaker->import (new_with_init => 'new',
424                             new_hash_init => 'hash_init',);
425
426 sub init {
427   my $self = shift;
428
429   # V1 Compatibility
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', })
435     if @_ == 2;
436
437   my $target;
438
439   croak
440     sprintf("Term::ProgressBar::new We don't handle this many arguments: %d",
441             scalar @_)
442     if @_ != 1;
443
444   my %config;
445
446   if ( UNIVERSAL::isa ($_[0], 'HASH') ) {
447     ($target) = @{$_[0]}{qw(count)};
448     %config = %{$_[0]}; # Copy in, so later playing does not tinker externally
449   } else {
450     ($target) = @_;
451   }
452
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');
456   }
457
458   croak "Target count required for Term::ProgressBar new\n"
459     unless defined $target;
460
461   $config{$_} = DEFAULTS->{$_}
462     for grep ! exists $config{$_}, keys %{DEFAULTS()};
463   delete $config{count};
464
465   $config{term} = -t $config{fh}
466     unless defined $config{term};
467
468   if ( $__FORCE_TERM ) {
469     $config{term} = 1;
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;
476   }
477
478   unless ( defined $config{bar_width} ) {
479     if ( defined $config{term_width} ) {
480       # 5 for the % marker
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;
492       }
493 #    } elsif ( ! $config{term} ) {
494 #      $config{bar_width}  = 1;
495 #      $config{term_width} = defined $config{ETA} ? 12 : 5;
496     } else {
497       $config{bar_width}  = $target;
498       die "configured bar_width $config{bar_width} < 1"
499         if $config{bar_width} < 1;
500     }
501   }
502
503   $config{start} = time;
504
505   select(((select $config{fh}), $| = 1)[0]);
506
507   $self->ETA(delete $config{ETA});
508
509   $self->hash_init (%config,
510
511                     offset        => 0,
512                     scale         => 1,
513
514                     last_update   => 0,
515                     last_position => 0,
516                    );
517   $self->target($target);
518   $self->minor($config{term} && $target > $config{bar_width} ** 1.5);
519
520   $self->update(0); # Initialize the progress bar
521 }
522
523
524 # ----------------------------------
525 # INSTANCE FINALIZATION
526 # ----------------------------------
527
528 # ----------------------------------
529 # INSTANCE COMPONENTS
530 # ----------------------------------
531
532 =head1 INSTANCE COMPONENTS
533
534 =cut
535
536 =head2 Scalar Components.
537
538 See L<Class::MethodMaker/get_set> for usage.
539
540 =over 4
541
542 =item target
543
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
547
548   $p = Term::ProgressBar({count => 20});
549   # Halfway
550   $p->update(10);
551   # Double scale
552   $p->target(40)
553   $p->update(21);
554
555 will cause the progress bar to update to 52.5%
556
557 =item max_update_rate
558
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.
562
563 =back
564
565 =head2 Boolean Components
566
567 See L<Class::MethodMaker/get_set> for usage.
568
569 =over 4
570
571 =item minor
572
573 Default: set.  If unset, no minor scale will be calculated or updated.
574
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">.
582
583 See F<examples/powers4> and F<examples/powers3> to see minor characters in
584 action, and not in action, respectively.
585
586 =back
587
588 =head2 Configuration
589
590 =over 4
591
592 =item lbrack
593
594 Left bracket ( defaults to [ )
595
596  $progress->lbrack('<');
597
598 =item rbrack
599
600 Right bracket ( defaults to ] )
601
602  $progress->rbrack('>');
603
604 =back
605
606 =cut
607
608 # Private Scalar Components
609 #  offset    ) Default: 0.       Added to any value supplied to update.
610 #  scale     ) Default: 1.       Any value supplied to update is multiplied by
611 #                                this.
612 #  major_char) Default: '='.     The character printed for the major scale.
613 #  minor_char) Default: '*'.     The character printed for the minor scale.
614 #  name      ) Default: undef.   The name to print to the side of the bar.
615 #  fh        ) Default: STDERR.  The filehandle to output progress to.
616
617 # Private Counter Components
618 #  last_update  ) Default: 0.    The so_far value last time update was invoked.
619 #  last_position) Default: 0.    The number of the last progress mark printed.
620
621 # Private Boolean Components
622 #  term      ) Default: detected (by C<Term::ReadKey>).
623 #              If unset, we assume that we are not connected to a terminal (or
624 #              at least, not a suitably intelligent one).  Then, we attempt
625 #              minimal functionality.
626
627 Class::MethodMaker->import
628   (
629    get_set       => [qw/ major_units major_char
630                          minor_units minor_char
631                          lbrack      rbrack
632                          name
633                          offset      scale
634                          fh          start
635                          max_update_rate
636                      /],
637    counter       => [qw/ last_position last_update /],
638    boolean       => [qw/ minor name_printed pb_ended remove /],
639    # let it be boolean to handle 0 but true
640    get_set       => [qw/ term /],
641   );
642
643 # We generate these by hand since we want to check the values.
644 sub bar_width {
645     my $self = shift;
646     return $self->{bar_width} if not @_;
647     croak 'wrong number of arguments' if @_ != 1;
648     croak 'bar_width < 1' if $_[0] < 1;
649     $self->{bar_width} = $_[0];
650 }
651 sub term_width {
652     my $self = shift;
653     return $self->{term_width} if not @_;
654     croak 'wrong number of arguments' if @_ != 1;
655     croak 'term_width must be at least 5' if $self->term and $_[0] < 5;
656     $self->{term_width} = $_[0];
657 }
658
659 sub target {
660   my $self = shift;
661
662   if ( @_ ) {
663     my ($target) = @_;
664
665     if ( $target ) {
666       $self->major_units($self->bar_width / $target);
667       $self->minor_units($self->bar_width ** 2 / $target);
668       $self->minor      ( defined $self->term_width   and
669                           $self->term_width < $target );
670     }
671     $self->{target}  = $target;
672   }
673
674   return $self->{target};
675 }
676
677 sub ETA {
678   my $self = shift;
679
680   if (@_) {
681     my ($type) = @_;
682     croak "Invalid ETA type: $type\n"
683       if defined $type and ! exists ETA_TYPES->{$type};
684     $self->{ETA} = $type;
685   }
686
687   return $self->{ETA};
688 }
689
690 # ----------------------------------
691 # INSTANCE HIGHER-LEVEL FUNCTIONS
692 # ----------------------------------
693
694 # ----------------------------------
695 # INSTANCE HIGHER-LEVEL PROCEDURES
696 # ----------------------------------
697
698 =head1 INSTANCE HIGHER-LEVEL PROCEDURES
699
700 Z<>
701
702 =cut
703
704 sub no_minor {
705   warn sprintf("%s: This method is deprecated.  Please use %s instead\n",
706                (caller (0))[3], '$x->minor (0)',);
707   $_[0]->clear_minor (0);
708 }
709
710 # -------------------------------------
711
712 =head2 update
713
714 Update the progress bar.
715
716 =over 4
717
718 =item ARGUMENTS
719
720 =over 4
721
722 =item so_far
723
724 Current progress point, in whatever units were passed to C<new>.
725
726 If not defined, assumed to be 1+ whatever was the value last time C<update>
727 was called (starting at 0).
728
729 =back
730
731 =item RETURNS
732
733 =over 4
734
735 =item next_call
736
737 The next value of so_far at which to call C<update>.
738
739 =back
740
741 =back
742
743 =cut
744
745 sub update {
746   my $self = shift;
747   my ($so_far) = @_;
748
749   if ( ! defined $so_far ) {
750     $so_far = $self->last_update + 1;
751   }
752
753   my $input_so_far = $so_far;
754   $so_far *= $self->scale
755     unless $self->scale == 1;
756   $so_far += $self->offset;
757
758   my $target = my $next = $self->target;
759   my $name = $self->name;
760   my $fh = $self->fh;
761
762   if ( $target < 1 ) {
763     print $fh "\r";
764     printf $fh "$name: "
765       if defined $name;
766     print $fh "(nothing to do)\n";
767     return 2**32-1;
768   }
769
770   my $biggies     = $self->major_units * $so_far;
771   my @chars = (' ') x $self->bar_width;
772   $chars[$_] = $self->major_char
773     for 0..$biggies-1;
774
775   if ( $self->minor ) {
776     my $smally      = $self->minor_units * $so_far % $self->bar_width;
777     $chars[$smally] = $self->minor_char
778       unless $so_far == $target;
779     $next *= ($self->minor_units * $so_far + 1) / ($self->bar_width ** 2);
780   } else {
781     $next *= ($self->major_units * $so_far + 1) / $self->bar_width;
782   }
783
784   local $\ = undef;
785
786   if ( $self->term > 0 ) {
787     local $\ = undef;
788     my $to_print = "\r";
789     $to_print .= "$name: "
790       if defined $name;
791     my $ratio = $so_far / $target;
792     # Rounds down %
793     $to_print .= (sprintf ("%3d%% %s%s%s",
794                         $ratio * 100,
795                         $self->lbrack, join ('', @chars), $self->rbrack));
796     my $ETA = $self->ETA;
797     if ( defined $ETA and $ratio > 0 ) {
798       if ( $ETA eq 'linear' ) {
799         if ( $ratio == 1 ) {
800           my $taken = time - $self->start;
801           my $ss    = $taken % 60;
802           my $mm    = int(($taken % 3600) / 60);
803           my $hh    = int($taken / 3600);
804           if ( $hh > 99 ) {
805             $to_print .= sprintf('D %2dh%02dm', $hh, $mm, $ss);
806           } else {
807             $to_print .= sprintf('D%2dh%02dm%02ds', $hh, $mm, $ss);
808           }
809         } elsif ( $ratio < PREDICT_RATIO ) {
810           # No safe prediction yet
811           $to_print .= 'ETA ------';
812         } else {
813           my $time = time;
814           my $left = (($time - $self->start) * ((1 - $ratio) / $ratio));
815           if ( $left  < ETA_TIME_CUTOFF ) {
816             $to_print .= sprintf '%1dm%02ds Left', int($left / 60), $left % 60;
817           } else {
818             my $eta  = $time + $left;
819             my $format;
820             if ( $left < DAY ) {
821               $format = 'ETA  %H:%M';
822             } elsif ( $left < ETA_DATE_CUTOFF ) {
823               $format = sprintf('ETA %%l%%p+%d',$left/DAY);
824             } else {
825               $format = 'ETA %e%b';
826             }
827             $to_print .= strftime($format, localtime $eta);
828           }
829           # Calculate next to be at least SEC_PER_UPDATE seconds away
830           if ( $left > 0 ) {
831             my $incr = ($target - $so_far) / ($left / $self->max_update_rate);
832             $next = $so_far + $incr
833               if $so_far + $incr > $next;
834           }
835         }
836       } else {
837         croak "Bad ETA type: $ETA\n";
838       }
839     }
840     for ($self->{last_printed}) {
841         unless (defined and $_ eq $to_print) {
842             print $fh $to_print;
843         }
844         $_ = $to_print;
845     }
846
847     $next -= $self->offset;
848     $next /= $self->scale
849       unless $self->scale == 1;
850
851     if ( $so_far >= $target and $self->remove and ! $self->pb_ended) {
852       print $fh "\r", ' ' x $self->term_width, "\r";
853       $self->pb_ended;
854     }
855
856   } else {
857     local $\ = undef;
858
859     if ( $self->term ) { # special case for backwards compat.
860      if ( $so_far == 0 and defined $name and ! $self->name_printed ) {
861        print $fh "$name: ";
862        $self->set_name_printed;
863      }
864
865       my $position = int($self->bar_width * ($input_so_far / $target));
866       my $add      = $position - $self->last_position;
867       $self->last_position_incr ($add)
868         if $add;
869
870      print $fh $self->major_char x $add;
871
872      $next -= $self->offset;
873      $next /= $self->scale
874        unless $self->scale == 1;
875     } else {
876       my $pc = int(100*$input_so_far/$target);
877       printf $fh "[%s] %s: %3d%%\n", scalar(localtime), $name, $pc;
878
879       $next = ceil($target * ($pc+1)/100);
880     }
881
882     if ( $input_so_far >= $target ) {
883       if ( $self->pb_ended ) {
884         croak ALREADY_FINISHED;
885       } else {
886         if ( $self->term ) {
887           print $fh "\n"
888         }
889         $self->set_pb_ended;
890       }
891     }
892   }
893
894
895   $next = $target if $next > $target;
896
897   $self->last_update($input_so_far);
898   return $next;
899 }
900
901 # -------------------------------------
902
903 =head2 message
904
905 Output a message.  This is very much like print, but we try not to disturb the
906 terminal.
907
908 =over 4
909
910 =item ARGUMENTS
911
912 =over 4
913
914 =item string
915
916 The message to output.
917
918 =back
919
920 =back
921
922 =cut
923
924 sub message {
925   my $self = shift;
926   my ($string) = @_;
927   chomp ($string);
928
929   my $fh = $self->fh;
930   local $\ = undef;
931   if ( $self->term ) {
932     print $fh "\r", ' ' x $self->term_width;
933     print $fh "\r$string\n";
934   } else {
935     print $fh "\n$string\n";
936     print $fh $self->major_char x $self->last_position;
937   }
938   undef $self->{last_printed};
939   $self->update($self->last_update);
940 }
941
942
943 # ----------------------------------------------------------------------
944
945 =head1 BUGS
946
947 Z<>
948
949 =head1 REPORTING BUGS
950
951 Email the author.
952
953 =head1 COMPATIBILITY
954
955 If exactly two arguments are provided, then L<new|"new"> operates in v1
956 compatibility mode: the arguments are considered to be name, and item count.
957 Various other defaults are set to emulate version one (e.g., the major output
958 character is '#', the bar width is set to 50 characters and the output
959 filehandle is not treated as a terminal). This mode is deprecated.
960
961 =head1  AUTHOR
962
963 Martyn J. Pearce fluffy@cpan.org
964
965 Significant contributions from Ed Avis, amongst others.
966
967 =head1 COPYRIGHT
968
969 Copyright (c) 2001, 2002, 2003, 2004, 2005 Martyn J. Pearce.  This program is
970 free software; you can redistribute it and/or modify it under the same terms
971 as Perl itself.
972
973 =head1  SEE ALSO
974
975 Z<>
976
977 =cut
978
979 1; # keep require happy.
980
981 __END__