]> git.donarmstrong.com Git - term-progressbar.git/blob - lib/Term/ProgressBar.pm
f1ed1dc1e3fe3b1414d32ec18a803a44000464b3
[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 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.
82
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).
85
86 =head2 A smoother bar update
87
88   my $progress = Term::ProgressBar->new($max);
89
90   for (0..$max) {
91     my $is_power = 0;
92     for(my $i = 0; 2**$i <= $_; $i++) {
93       $is_power = 1
94         if 2**$i == $_;
95     }
96
97     $progress->update($_)
98   }
99
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
105 finished bar.
106
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.
109
110 =head2 A (much) more efficient update
111
112   my $progress = Term::ProgressBar->new({name => 'Powers', count => $max, remove => 1});
113   $progress->minor(0);
114   my $next_update = 0;
115
116   for (0..$max) {
117     my $is_power = 0;
118     for(my $i = 0; 2**$i <= $_; $i++) {
119       $is_power = 1
120         if 2**$i == $_;
121     }
122
123     $next_update = $progress->update($_)
124       if $_ >= $next_update;
125   }
126   $progress->update($max)
127     if $max >= $next_update;
128
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.
135
136 This example also sets the name of the progress bar.
137
138 This example also demonstrates the use of the 'remove' flag, which removes the
139 progress bar from the terminal when done.
140
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.
143
144 =head2 Using Completion Time Estimation
145
146   my $progress = Term::ProgressBar->new({name  => 'Powers',
147                                          count => $max,
148                                          ETA   => linear, });
149   $progress->max_update_rate(1);
150   my $next_update = 0;
151
152   for (0..$max) {
153     my $is_power = 0;
154     for(my $i = 0; 2**$i <= $_; $i++) {
155       if ( 2**$i == $_ ) {
156         $is_power = 1;
157         $progress->message(sprintf "Found %8d to be 2 ** %2d", $_, $i);
158       }
159     }
160
161     $next_update = $progress->update($_)
162       if $_ > $next_update;
163   }
164   $progress->update($max)
165       if $max >= $next_update;
166
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.
171
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
174
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.
177
178 =cut
179
180 # ----------------------------------------------------------------------
181
182 # Pragmas --------------------------
183
184 use strict;
185
186 # Inheritance ----------------------
187
188 use base qw( Exporter );
189 use vars '@EXPORT_OK';
190 @EXPORT_OK = qw( $PACKAGE $VERSION );
191
192 # Utility --------------------------
193
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 );
198
199 # ----------------------------------------------------------------------
200
201 # CLASS METHODS --------------------------------------------------------
202
203 # ----------------------------------
204 # CLASS CONSTANTS
205 # ----------------------------------
206
207 =head1 CLASS CONSTANTS
208
209 Z<>
210
211 =cut
212
213 use constant MINUTE => 60;
214 use constant HOUR   => 60 * MINUTE;
215 use constant DAY    => 24 * HOUR;
216
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;
223
224 use constant DEFAULTS => {
225                           lbrack     => '[',
226                           rbrack     => ']',
227                           minor_char => '*',
228                           major_char => '=',
229                           fh         => \*STDERR,
230                           name       => undef,
231                           ETA        => undef,
232                           max_update_rate => 0.5,
233
234                           # The following defaults are never used, but the keys
235                           # are valuable for error checking
236                           count      => undef,
237                           bar_width  => undef,
238                           term_width => undef,
239                           term       => undef,
240                           remove     => 0,
241                          };
242
243 use constant ETA_TYPES => { map { $_ => 1 } qw( linear ) };
244
245 use constant ALREADY_FINISHED => 'progress bar already finished';
246
247 use constant DEBUG => 0;
248
249 # -------------------------------------
250
251 use vars qw($PACKAGE $VERSION);
252 $PACKAGE = 'Term-ProgressBar';
253 $VERSION = '2.09';
254
255 # ----------------------------------
256 # CLASS CONSTRUCTION
257 # ----------------------------------
258
259 # ----------------------------------
260 # CLASS COMPONENTS
261 # ----------------------------------
262
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;
266
267 # ----------------------------------
268 # CLASS HIGHER-LEVEL FUNCTIONS
269 # ----------------------------------
270
271 # ----------------------------------
272 # CLASS HIGHER-LEVEL PROCEDURES
273 # ----------------------------------
274
275 sub __force_term {
276   my $class = shift;
277   ($__FORCE_TERM) = @_;
278 }
279
280 # ----------------------------------
281 # CLASS UTILITY FUNCTIONS
282 # ----------------------------------
283
284 sub term_size {
285   my ($fh) = @_;
286
287   eval {
288     require Term::ReadKey;
289   }; if ($@) {
290     warn "Guessing terminal width due to problem with Term::ReadKey\n";
291     return 50;
292   }
293
294   my $result;
295   eval {
296     $result = (Term::ReadKey::GetTerminalSize($fh))[0];
297     $result-- if ($^O eq "MSWin32");
298   }; if ( $@ ) {
299     warn "error from Term::ReadKey::GetTerminalSize(): $@";
300   }
301
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
305   # zero.
306   #
307   if ( ! $result ) {
308     $result = 50;
309     warn "guessing terminal width $result\n";
310   }
311
312   return $result;
313 }
314
315
316 # INSTANCE METHODS -----------------------------------------------------
317
318 # ----------------------------------
319 # INSTANCE CONSTRUCTION
320 # ----------------------------------
321
322 =head1 INSTANCE CONSTRUCTION
323
324 Z<>
325
326 =cut
327
328 # Don't document hash keys until tested that the give the desired affect!
329
330 =head2 new
331
332 Create & return a new Term::ProgressBar instance.
333
334 =over 4
335
336 =item ARGUMENTS
337
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.
341
342 =over 4
343
344 =item count
345
346 The item count.  The progress is marked at 100% when update I<count> is
347 invoked, and proportionally until then.
348
349 =item name
350
351 A name to prefix the progress bar with.
352
353 =item fh
354
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
357 globref instead.
358
359 =item ETA
360
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
365
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.
370
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'>.
378
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.
385
386 The available values for this are:
387
388 =over 4
389
390 =item undef
391
392 Do not do estimation.  The default.
393
394 =item linear
395
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.
399
400 =back
401
402 =back
403
404 =item EXAMPLES
405
406   my $progress = Term::ProgressBar->new(100); # count from 1 to 100
407   my $progress = Term::ProgressBar->new({ count => 100 }); # same
408
409   # Count to 200 thingies, outputting to stdout instead of stderr,
410   # prefix bar with 'thingy'
411   my $progress = Term::ProgressBar->new({ count => 200,
412                                           fh    => \*STDOUT,
413                                           name  => 'thingy' });
414
415 =back
416
417 =cut
418
419 Class::MethodMaker->import (new_with_init => 'new',
420                             new_hash_init => 'hash_init',);
421
422 sub init {
423   my $self = shift;
424
425   # V1 Compatibility
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', })
431     if @_ == 2;
432
433   my $target;
434
435   croak
436     sprintf("Term::ProgressBar::new We don't handle this many arguments: %d",
437             scalar @_)
438     if @_ != 1;
439
440   my %config;
441
442   if ( UNIVERSAL::isa ($_[0], 'HASH') ) {
443     ($target) = @{$_[0]}{qw(count)};
444     %config = %{$_[0]}; # Copy in, so later playing does not tinker externally
445   } else {
446     ($target) = @_;
447   }
448
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');
452   }
453
454   croak "Target count required for Term::ProgressBar new\n"
455     unless defined $target;
456
457   $config{$_} = DEFAULTS->{$_}
458     for grep ! exists $config{$_}, keys %{DEFAULTS()};
459   delete $config{count};
460
461   $config{term} = -t $config{fh}
462     unless defined $config{term};
463
464   if ( $__FORCE_TERM ) {
465     $config{term} = 1;
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;
472   }
473
474   unless ( defined $config{bar_width} ) {
475     if ( defined $config{term_width} ) {
476       # 5 for the % marker
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;
488       }
489 #    } elsif ( ! $config{term} ) {
490 #      $config{bar_width}  = 1;
491 #      $config{term_width} = defined $config{ETA} ? 12 : 5;
492     } else {
493       $config{bar_width}  = $target;
494       die "configured bar_width $config{bar_width} < 1"
495         if $config{bar_width} < 1;
496     }
497   }
498
499   $config{start} = time;
500
501   select(((select $config{fh}), $| = 1)[0]);
502
503   $self->ETA(delete $config{ETA});
504
505   $self->hash_init (%config,
506
507                     offset        => 0,
508                     scale         => 1,
509
510                     last_update   => 0,
511                     last_position => 0,
512                    );
513   $self->target($target);
514   $self->minor($config{term} && $target > $config{bar_width} ** 1.5);
515
516   $self->update(0); # Initialize the progress bar
517 }
518
519
520 # ----------------------------------
521 # INSTANCE FINALIZATION
522 # ----------------------------------
523
524 # ----------------------------------
525 # INSTANCE COMPONENTS
526 # ----------------------------------
527
528 =head1 INSTANCE COMPONENTS
529
530 =cut
531
532 =head2 Scalar Components.
533
534 See L<Class::MethodMaker/get_set> for usage.
535
536 =over 4
537
538 =item target
539
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
543
544   $p = Term::ProgressBar({count => 20});
545   # Halfway
546   $p->update(10);
547   # Double scale
548   $p->target(40)
549   $p->update(21);
550
551 will cause the progress bar to update to 52.5%
552
553 =item max_update_rate
554
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.
558
559 =back
560
561 =head2 Boolean Components
562
563 See L<Class::MethodMaker/get_set> for usage.
564
565 =over 4
566
567 =item minor
568
569 Default: set.  If unset, no minor scale will be calculated or updated.
570
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">.
578
579 See F<examples/powers4> and F<examples/powers3> to see minor characters in
580 action, and not in action, respectively.
581
582 =back
583
584 =cut
585
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
589 #                                this.
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.
594
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.
598
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.
604
605 Class::MethodMaker->import
606   (
607    get_set       => [qw/ major_units major_char
608                          minor_units minor_char
609                          lbrack      rbrack
610                          name
611                          offset      scale
612                          fh          start
613                          max_update_rate
614                      /],
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 /],
619   );
620
621 # We generate these by hand since we want to check the values.
622 sub bar_width {
623     my $self = shift;
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];
628 }
629 sub term_width {
630     my $self = shift;
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];
635 }
636
637 sub target {
638   my $self = shift;
639
640   if ( @_ ) {
641     my ($target) = @_;
642
643     if ( $target ) {
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 );
648     }
649     $self->{target}  = $target;
650   }
651
652   return $self->{target};
653 }
654
655 sub ETA {
656   my $self = shift;
657
658   if (@_) {
659     my ($type) = @_;
660     croak "Invalid ETA type: $type\n"
661       if defined $type and ! exists ETA_TYPES->{$type};
662     $self->{ETA} = $type;
663   }
664
665   return $self->{ETA};
666 }
667
668 # ----------------------------------
669 # INSTANCE HIGHER-LEVEL FUNCTIONS
670 # ----------------------------------
671
672 # ----------------------------------
673 # INSTANCE HIGHER-LEVEL PROCEDURES
674 # ----------------------------------
675
676 =head1 INSTANCE HIGHER-LEVEL PROCEDURES
677
678 Z<>
679
680 =cut
681
682 sub no_minor {
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);
686 }
687
688 # -------------------------------------
689
690 =head2 update
691
692 Update the progress bar.
693
694 =over 4
695
696 =item ARGUMENTS
697
698 =over 4
699
700 =item so_far
701
702 Current progress point, in whatever units were passed to C<new>.
703
704 If not defined, assumed to be 1+ whatever was the value last time C<update>
705 was called (starting at 0).
706
707 =back
708
709 =item RETURNS
710
711 =over 4
712
713 =item next_call
714
715 The next value of so_far at which to call C<update>.
716
717 =back
718
719 =back
720
721 =cut
722
723 sub update {
724   my $self = shift;
725   my ($so_far) = @_;
726
727   if ( ! defined $so_far ) {
728     $so_far = $self->last_update + 1;
729   }
730
731   my $input_so_far = $so_far;
732   $so_far *= $self->scale
733     unless $self->scale == 1;
734   $so_far += $self->offset;
735
736   my $target = my $next = $self->target;
737   my $name = $self->name;
738   my $fh = $self->fh;
739
740   if ( $target < 1 ) {
741     print $fh "\r";
742     printf $fh "$name: "
743       if defined $name;
744     print $fh "(nothing to do)\n";
745     return 2**32-1;
746   }
747
748   my $biggies     = $self->major_units * $so_far;
749   my @chars = (' ') x $self->bar_width;
750   $chars[$_] = $self->major_char
751     for 0..$biggies-1;
752
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);
758   } else {
759     $next *= ($self->major_units * $so_far + 1) / $self->bar_width;
760   }
761
762   local $\ = undef;
763
764   if ( $self->term > 0 ) {
765     local $\ = undef;
766     my $to_print = "\r";
767     $to_print .= "$name: "
768       if defined $name;
769     my $ratio = $so_far / $target;
770     # Rounds down %
771     $to_print .= (sprintf ("%3d%% %s%s%s",
772                         $ratio * 100,
773                         $self->lbrack, join ('', @chars), $self->rbrack));
774     my $ETA = $self->ETA;
775     if ( defined $ETA and $ratio > 0 ) {
776       if ( $ETA eq 'linear' ) {
777         if ( $ratio == 1 ) {
778           my $taken = time - $self->start;
779           my $ss    = $taken % 60;
780           my $mm    = int(($taken % 3600) / 60);
781           my $hh    = int($taken / 3600);
782           if ( $hh > 99 ) {
783             $to_print .= sprintf('D %2dh%02dm', $hh, $mm, $ss);
784           } else {
785             $to_print .= sprintf('D%2dh%02dm%02ds', $hh, $mm, $ss);
786           }
787         } elsif ( $ratio < PREDICT_RATIO ) {
788           # No safe prediction yet
789           $to_print .= 'ETA ------';
790         } else {
791           my $time = time;
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;
795           } else {
796             my $eta  = $time + $left;
797             my $format;
798             if ( $left < DAY ) {
799               $format = 'ETA  %H:%M';
800             } elsif ( $left < ETA_DATE_CUTOFF ) {
801               $format = sprintf('ETA %%l%%p+%d',$left/DAY);
802             } else {
803               $format = 'ETA %e%b';
804             }
805             $to_print .= strftime($format, localtime $eta);
806           }
807           # Calculate next to be at least SEC_PER_UPDATE seconds away
808           if ( $left > 0 ) {
809             my $incr = ($target - $so_far) / ($left / $self->max_update_rate);
810             $next = $so_far + $incr
811               if $so_far + $incr > $next;
812           }
813         }
814       } else {
815         croak "Bad ETA type: $ETA\n";
816       }
817     }
818     for ($self->{last_printed}) {
819         unless (defined and $_ eq $to_print) {
820             print $fh $to_print;
821         }
822         $_ = $to_print;
823     }
824
825     $next -= $self->offset;
826     $next /= $self->scale
827       unless $self->scale == 1;
828
829     if ( $so_far >= $target and $self->remove and ! $self->pb_ended) {
830       print $fh "\r", ' ' x $self->term_width, "\r";
831       $self->pb_ended;
832     }
833
834   } else {
835     local $\ = undef;
836
837     if ( $self->term ) { # special case for backwards compat.
838      if ( $so_far == 0 and defined $name and ! $self->name_printed ) {
839        print $fh "$name: ";
840        $self->set_name_printed;
841      }
842
843       my $position = int($self->bar_width * ($input_so_far / $target));
844       my $add      = $position - $self->last_position;
845       $self->last_position_incr ($add)
846         if $add;
847
848      print $fh $self->major_char x $add;
849
850      $next -= $self->offset;
851      $next /= $self->scale
852        unless $self->scale == 1;
853     } else {
854       my $pc = int(100*$input_so_far/$target);
855       printf $fh "[%s] %s: %3d%%\n", scalar(localtime), $name, $pc;
856
857       $next = ceil($target * ($pc+1)/100);
858     }
859
860     if ( $input_so_far >= $target ) {
861       if ( $self->pb_ended ) {
862         croak ALREADY_FINISHED;
863       } else {
864         if ( $self->term ) {
865           print $fh "\n"
866         }
867         $self->set_pb_ended;
868       }
869     }
870   }
871
872
873   $next = $target if $next > $target;
874
875   $self->last_update($input_so_far);
876   return $next;
877 }
878
879 # -------------------------------------
880
881 =head2 message
882
883 Output a message.  This is very much like print, but we try not to disturb the
884 terminal.
885
886 =over 4
887
888 =item ARGUMENTS
889
890 =over 4
891
892 =item string
893
894 The message to output.
895
896 =back
897
898 =back
899
900 =cut
901
902 sub message {
903   my $self = shift;
904   my ($string) = @_;
905   chomp ($string);
906
907   my $fh = $self->fh;
908   local $\ = undef;
909   if ( $self->term ) {
910     print $fh "\r", ' ' x $self->term_width;
911     print $fh "\r$string\n";
912   } else {
913     print $fh "\n$string\n";
914     print $fh $self->major_char x $self->last_position;
915   }
916   undef $self->{last_printed};
917   $self->update($self->last_update);
918 }
919
920
921 # ----------------------------------------------------------------------
922
923 =head1 BUGS
924
925 Z<>
926
927 =head1 REPORTING BUGS
928
929 Email the author.
930
931 =head1 COMPATIBILITY
932
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.
938
939 =head1  AUTHOR
940
941 Martyn J. Pearce fluffy@cpan.org
942
943 Significant contributions from Ed Avis, amongst others.
944
945 =head1 COPYRIGHT
946
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
949 as Perl itself.
950
951 =head1  SEE ALSO
952
953 Z<>
954
955 =cut
956
957 1; # keep require happy.
958
959 __END__