]> git.donarmstrong.com Git - term-progressbar.git/blob - lib/Term/ProgressBar.pm
84ed9b805b203e6bd7ebaa5942aea836579435f7
[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.09';
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 =cut
589
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
593 #                                this.
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.
598
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.
602
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.
608
609 Class::MethodMaker->import
610   (
611    get_set       => [qw/ major_units major_char
612                          minor_units minor_char
613                          lbrack      rbrack
614                          name
615                          offset      scale
616                          fh          start
617                          max_update_rate
618                      /],
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 /],
623   );
624
625 # We generate these by hand since we want to check the values.
626 sub bar_width {
627     my $self = shift;
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];
632 }
633 sub term_width {
634     my $self = shift;
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];
639 }
640
641 sub target {
642   my $self = shift;
643
644   if ( @_ ) {
645     my ($target) = @_;
646
647     if ( $target ) {
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 );
652     }
653     $self->{target}  = $target;
654   }
655
656   return $self->{target};
657 }
658
659 sub ETA {
660   my $self = shift;
661
662   if (@_) {
663     my ($type) = @_;
664     croak "Invalid ETA type: $type\n"
665       if defined $type and ! exists ETA_TYPES->{$type};
666     $self->{ETA} = $type;
667   }
668
669   return $self->{ETA};
670 }
671
672 # ----------------------------------
673 # INSTANCE HIGHER-LEVEL FUNCTIONS
674 # ----------------------------------
675
676 # ----------------------------------
677 # INSTANCE HIGHER-LEVEL PROCEDURES
678 # ----------------------------------
679
680 =head1 INSTANCE HIGHER-LEVEL PROCEDURES
681
682 Z<>
683
684 =cut
685
686 sub no_minor {
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);
690 }
691
692 # -------------------------------------
693
694 =head2 update
695
696 Update the progress bar.
697
698 =over 4
699
700 =item ARGUMENTS
701
702 =over 4
703
704 =item so_far
705
706 Current progress point, in whatever units were passed to C<new>.
707
708 If not defined, assumed to be 1+ whatever was the value last time C<update>
709 was called (starting at 0).
710
711 =back
712
713 =item RETURNS
714
715 =over 4
716
717 =item next_call
718
719 The next value of so_far at which to call C<update>.
720
721 =back
722
723 =back
724
725 =cut
726
727 sub update {
728   my $self = shift;
729   my ($so_far) = @_;
730
731   if ( ! defined $so_far ) {
732     $so_far = $self->last_update + 1;
733   }
734
735   my $input_so_far = $so_far;
736   $so_far *= $self->scale
737     unless $self->scale == 1;
738   $so_far += $self->offset;
739
740   my $target = my $next = $self->target;
741   my $name = $self->name;
742   my $fh = $self->fh;
743
744   if ( $target < 1 ) {
745     print $fh "\r";
746     printf $fh "$name: "
747       if defined $name;
748     print $fh "(nothing to do)\n";
749     return 2**32-1;
750   }
751
752   my $biggies     = $self->major_units * $so_far;
753   my @chars = (' ') x $self->bar_width;
754   $chars[$_] = $self->major_char
755     for 0..$biggies-1;
756
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);
762   } else {
763     $next *= ($self->major_units * $so_far + 1) / $self->bar_width;
764   }
765
766   local $\ = undef;
767
768   if ( $self->term > 0 ) {
769     local $\ = undef;
770     my $to_print = "\r";
771     $to_print .= "$name: "
772       if defined $name;
773     my $ratio = $so_far / $target;
774     # Rounds down %
775     $to_print .= (sprintf ("%3d%% %s%s%s",
776                         $ratio * 100,
777                         $self->lbrack, join ('', @chars), $self->rbrack));
778     my $ETA = $self->ETA;
779     if ( defined $ETA and $ratio > 0 ) {
780       if ( $ETA eq 'linear' ) {
781         if ( $ratio == 1 ) {
782           my $taken = time - $self->start;
783           my $ss    = $taken % 60;
784           my $mm    = int(($taken % 3600) / 60);
785           my $hh    = int($taken / 3600);
786           if ( $hh > 99 ) {
787             $to_print .= sprintf('D %2dh%02dm', $hh, $mm, $ss);
788           } else {
789             $to_print .= sprintf('D%2dh%02dm%02ds', $hh, $mm, $ss);
790           }
791         } elsif ( $ratio < PREDICT_RATIO ) {
792           # No safe prediction yet
793           $to_print .= 'ETA ------';
794         } else {
795           my $time = time;
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;
799           } else {
800             my $eta  = $time + $left;
801             my $format;
802             if ( $left < DAY ) {
803               $format = 'ETA  %H:%M';
804             } elsif ( $left < ETA_DATE_CUTOFF ) {
805               $format = sprintf('ETA %%l%%p+%d',$left/DAY);
806             } else {
807               $format = 'ETA %e%b';
808             }
809             $to_print .= strftime($format, localtime $eta);
810           }
811           # Calculate next to be at least SEC_PER_UPDATE seconds away
812           if ( $left > 0 ) {
813             my $incr = ($target - $so_far) / ($left / $self->max_update_rate);
814             $next = $so_far + $incr
815               if $so_far + $incr > $next;
816           }
817         }
818       } else {
819         croak "Bad ETA type: $ETA\n";
820       }
821     }
822     for ($self->{last_printed}) {
823         unless (defined and $_ eq $to_print) {
824             print $fh $to_print;
825         }
826         $_ = $to_print;
827     }
828
829     $next -= $self->offset;
830     $next /= $self->scale
831       unless $self->scale == 1;
832
833     if ( $so_far >= $target and $self->remove and ! $self->pb_ended) {
834       print $fh "\r", ' ' x $self->term_width, "\r";
835       $self->pb_ended;
836     }
837
838   } else {
839     local $\ = undef;
840
841     if ( $self->term ) { # special case for backwards compat.
842      if ( $so_far == 0 and defined $name and ! $self->name_printed ) {
843        print $fh "$name: ";
844        $self->set_name_printed;
845      }
846
847       my $position = int($self->bar_width * ($input_so_far / $target));
848       my $add      = $position - $self->last_position;
849       $self->last_position_incr ($add)
850         if $add;
851
852      print $fh $self->major_char x $add;
853
854      $next -= $self->offset;
855      $next /= $self->scale
856        unless $self->scale == 1;
857     } else {
858       my $pc = int(100*$input_so_far/$target);
859       printf $fh "[%s] %s: %3d%%\n", scalar(localtime), $name, $pc;
860
861       $next = ceil($target * ($pc+1)/100);
862     }
863
864     if ( $input_so_far >= $target ) {
865       if ( $self->pb_ended ) {
866         croak ALREADY_FINISHED;
867       } else {
868         if ( $self->term ) {
869           print $fh "\n"
870         }
871         $self->set_pb_ended;
872       }
873     }
874   }
875
876
877   $next = $target if $next > $target;
878
879   $self->last_update($input_so_far);
880   return $next;
881 }
882
883 # -------------------------------------
884
885 =head2 message
886
887 Output a message.  This is very much like print, but we try not to disturb the
888 terminal.
889
890 =over 4
891
892 =item ARGUMENTS
893
894 =over 4
895
896 =item string
897
898 The message to output.
899
900 =back
901
902 =back
903
904 =cut
905
906 sub message {
907   my $self = shift;
908   my ($string) = @_;
909   chomp ($string);
910
911   my $fh = $self->fh;
912   local $\ = undef;
913   if ( $self->term ) {
914     print $fh "\r", ' ' x $self->term_width;
915     print $fh "\r$string\n";
916   } else {
917     print $fh "\n$string\n";
918     print $fh $self->major_char x $self->last_position;
919   }
920   undef $self->{last_printed};
921   $self->update($self->last_update);
922 }
923
924
925 # ----------------------------------------------------------------------
926
927 =head1 BUGS
928
929 Z<>
930
931 =head1 REPORTING BUGS
932
933 Email the author.
934
935 =head1 COMPATIBILITY
936
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.
942
943 =head1  AUTHOR
944
945 Martyn J. Pearce fluffy@cpan.org
946
947 Significant contributions from Ed Avis, amongst others.
948
949 =head1 COPYRIGHT
950
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
953 as Perl itself.
954
955 =head1  SEE ALSO
956
957 Z<>
958
959 =cut
960
961 1; # keep require happy.
962
963 __END__