]> sjero.net Git - wget/blob - src/progress.c
[svn] Include ETA information in dot progress.
[wget] / src / progress.c
1 /* Download progress.
2    Copyright (C) 2001, 2002 Free Software Foundation, Inc.
3
4 This file is part of GNU Wget.
5
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
10
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with Wget; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 In addition, as a special exception, the Free Software Foundation
21 gives permission to link the code of its release of Wget with the
22 OpenSSL project's "OpenSSL" library (or with modified versions of it
23 that use the same license as the "OpenSSL" library), and distribute
24 the linked executables.  You must obey the GNU General Public License
25 in all respects for all of the code used other than "OpenSSL".  If you
26 modify this file, you may extend this exception to your version of the
27 file, but you are not obligated to do so.  If you do not wish to do
28 so, delete this exception statement from your version.  */
29
30 #include <config.h>
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <assert.h>
36 #ifdef HAVE_UNISTD_H
37 # include <unistd.h>
38 #endif
39 #include <signal.h>
40
41 #include "wget.h"
42 #include "progress.h"
43 #include "utils.h"
44 #include "retr.h"
45
46 struct progress_implementation {
47   const char *name;
48   bool interactive;
49   void *(*create) (wgint, wgint);
50   void (*update) (void *, wgint, double);
51   void (*finish) (void *, double);
52   void (*set_params) (const char *);
53 };
54
55 /* Necessary forward declarations. */
56
57 static void *dot_create (wgint, wgint);
58 static void dot_update (void *, wgint, double);
59 static void dot_finish (void *, double);
60 static void dot_set_params (const char *);
61
62 static void *bar_create (wgint, wgint);
63 static void bar_update (void *, wgint, double);
64 static void bar_finish (void *, double);
65 static void bar_set_params (const char *);
66
67 static struct progress_implementation implementations[] = {
68   { "dot", 0, dot_create, dot_update, dot_finish, dot_set_params },
69   { "bar", 1, bar_create, bar_update, bar_finish, bar_set_params }
70 };
71 static struct progress_implementation *current_impl;
72 static int current_impl_locked;
73
74 /* Progress implementation used by default.  Can be overriden in
75    wgetrc or by the fallback one.  */
76
77 #define DEFAULT_PROGRESS_IMPLEMENTATION "bar"
78
79 /* Fallback progress implementation should be something that works
80    under all display types.  If you put something other than "dot"
81    here, remember that bar_set_params tries to switch to this if we're
82    not running on a TTY.  So changing this to "bar" could cause
83    infloop.  */
84
85 #define FALLBACK_PROGRESS_IMPLEMENTATION "dot"
86
87 /* Return true if NAME names a valid progress bar implementation.  The
88    characters after the first : will be ignored.  */
89
90 bool
91 valid_progress_implementation_p (const char *name)
92 {
93   int i;
94   struct progress_implementation *pi = implementations;
95   char *colon = strchr (name, ':');
96   int namelen = colon ? colon - name : strlen (name);
97
98   for (i = 0; i < countof (implementations); i++, pi++)
99     if (!strncmp (pi->name, name, namelen))
100       return true;
101   return false;
102 }
103
104 /* Set the progress implementation to NAME.  */
105
106 void
107 set_progress_implementation (const char *name)
108 {
109   int i, namelen;
110   struct progress_implementation *pi = implementations;
111   const char *colon;
112
113   if (!name)
114     name = DEFAULT_PROGRESS_IMPLEMENTATION;
115
116   colon = strchr (name, ':');
117   namelen = colon ? colon - name : strlen (name);
118
119   for (i = 0; i < countof (implementations); i++, pi++)
120     if (!strncmp (pi->name, name, namelen))
121       {
122         current_impl = pi;
123         current_impl_locked = 0;
124
125         if (colon)
126           /* We call pi->set_params even if colon is NULL because we
127              want to give the implementation a chance to set up some
128              things it needs to run.  */
129           ++colon;
130
131         if (pi->set_params)
132           pi->set_params (colon);
133         return;
134       }
135   abort ();
136 }
137
138 static int output_redirected;
139
140 void
141 progress_schedule_redirect (void)
142 {
143   output_redirected = 1;
144 }
145
146 /* Create a progress gauge.  INITIAL is the number of bytes the
147    download starts from (zero if the download starts from scratch).
148    TOTAL is the expected total number of bytes in this download.  If
149    TOTAL is zero, it means that the download size is not known in
150    advance.  */
151
152 void *
153 progress_create (wgint initial, wgint total)
154 {
155   /* Check if the log status has changed under our feet. */
156   if (output_redirected)
157     {
158       if (!current_impl_locked)
159         set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
160       output_redirected = 0;
161     }
162
163   return current_impl->create (initial, total);
164 }
165
166 /* Return true if the progress gauge is "interactive", i.e. if it can
167    profit from being called regularly even in absence of data.  The
168    progress bar is interactive because it regularly updates the ETA
169    and current update.  */
170
171 bool
172 progress_interactive_p (void *progress)
173 {
174   return current_impl->interactive;
175 }
176
177 /* Inform the progress gauge of newly received bytes.  DLTIME is the
178    time in milliseconds since the beginning of the download.  */
179
180 void
181 progress_update (void *progress, wgint howmuch, double dltime)
182 {
183   current_impl->update (progress, howmuch, dltime);
184 }
185
186 /* Tell the progress gauge to clean up.  Calling this will free the
187    PROGRESS object, the further use of which is not allowed.  */
188
189 void
190 progress_finish (void *progress, double dltime)
191 {
192   current_impl->finish (progress, dltime);
193 }
194 \f
195 /* Dot-printing. */
196
197 struct dot_progress {
198   wgint initial_length;         /* how many bytes have been downloaded
199                                    previously. */
200   wgint total_length;           /* expected total byte count when the
201                                    download finishes */
202
203   int accumulated;              /* number of bytes accumulated after
204                                    the last printed dot */
205
206   int rows;                     /* number of rows printed so far */
207   int dots;                     /* number of dots printed in this row */
208
209   double last_timer_value;
210 };
211
212 /* Dot-progress backend for progress_create. */
213
214 static void *
215 dot_create (wgint initial, wgint total)
216 {
217   struct dot_progress *dp = xnew0 (struct dot_progress);
218   dp->initial_length = initial;
219   dp->total_length   = total;
220
221   if (dp->initial_length)
222     {
223       int dot_bytes = opt.dot_bytes;
224       const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
225
226       int remainder = dp->initial_length % ROW_BYTES;
227       wgint skipped = dp->initial_length - remainder;
228
229       if (skipped)
230         {
231           wgint skipped_k = skipped / 1024; /* skipped amount in K */
232           int skipped_k_len = numdigit (skipped_k);
233           if (skipped_k_len < 6)
234             skipped_k_len = 6;
235
236           /* Align the [ skipping ... ] line with the dots.  To do
237              that, insert the number of spaces equal to the number of
238              digits in the skipped amount in K.  */
239           logprintf (LOG_VERBOSE, _("\n%*s[ skipping %sK ]"),
240                      2 + skipped_k_len, "",
241                      number_to_static_string (skipped_k));
242         }
243
244       logprintf (LOG_VERBOSE, "\n%6sK",
245                  number_to_static_string (skipped / 1024));
246       for (; remainder >= dot_bytes; remainder -= dot_bytes)
247         {
248           if (dp->dots % opt.dot_spacing == 0)
249             logputs (LOG_VERBOSE, " ");
250           logputs (LOG_VERBOSE, ",");
251           ++dp->dots;
252         }
253       assert (dp->dots < opt.dots_in_line);
254
255       dp->accumulated = remainder;
256       dp->rows = skipped / ROW_BYTES;
257     }
258
259   return dp;
260 }
261
262 static const char *eta_to_human_short (int, bool);
263
264 /* Prints the stats (percentage of completion, speed, ETA) for current
265    row.  DLTIME is the time spent downloading the data in current
266    row.
267
268    #### This function is somewhat uglified by the fact that current
269    row and last row have somewhat different stats requirements.  It
270    might be worthwhile to split it to two different functions.  */
271
272 static void
273 print_row_stats (struct dot_progress *dp, double dltime, bool last)
274 {
275   const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
276
277   /* bytes_displayed is the number of bytes indicated to the user by
278      dots printed so far, includes the initially "skipped" amount */
279   wgint bytes_displayed = dp->rows * ROW_BYTES + dp->dots * opt.dot_bytes;
280
281   if (last)
282     /* For last row also count bytes accumulated after last dot */
283     bytes_displayed += dp->accumulated;
284
285   if (dp->total_length)
286     {
287       /* Round to floor value to provide gauge how much data *has*
288          been retrieved.  12.8% will round to 12% because the 13% mark
289          has not yet been reached.  100% is only shown when done.  */
290       int percentage = 100.0 * bytes_displayed / dp->total_length;
291       logprintf (LOG_VERBOSE, "%3d%%", percentage);
292     }
293
294   {
295     static char names[] = {' ', 'K', 'M', 'G'};
296     int units;
297     double rate;
298     wgint bytes_this_row;
299     if (!last)
300       bytes_this_row = ROW_BYTES;
301     else
302       /* For last row also include bytes accumulated after last dot.  */
303       bytes_this_row = dp->dots * opt.dot_bytes + dp->accumulated;
304     if (dp->rows == dp->initial_length / ROW_BYTES)
305       /* Don't count the portion of the row belonging to initial_length */
306       bytes_this_row -= dp->initial_length % ROW_BYTES;
307     rate = calc_rate (bytes_this_row, dltime - dp->last_timer_value, &units);
308     logprintf (LOG_VERBOSE, " %4.*f%c",
309                rate >= 100 ? 0 : rate >= 9.995 ? 1 : 2,
310                rate, names[units]);
311     dp->last_timer_value = dltime;
312   }
313
314   if (!last)
315     {
316       if (dp->total_length)
317         {
318           wgint bytes_remaining = dp->total_length - bytes_displayed;
319           /* The quantity downloaded in this download run. */
320           wgint bytes_sofar = bytes_displayed - dp->initial_length;
321           double secs_sofar = dltime / 1000;
322           int eta = (int) (secs_sofar * bytes_remaining / bytes_sofar + 0.5);
323           logprintf (LOG_VERBOSE, " %s", eta_to_human_short (eta, true));
324         }
325     }
326   else
327     {
328       /* When done, print the total download time */
329       double secs = dltime / 1000;
330       if (secs >= 10)
331         logprintf (LOG_VERBOSE, "=%s",
332                    eta_to_human_short ((int) (secs + 0.5), true));
333       else
334         logprintf (LOG_VERBOSE, "=%ss", print_decimal (secs));
335     }
336 }
337
338 /* Dot-progress backend for progress_update. */
339
340 static void
341 dot_update (void *progress, wgint howmuch, double dltime)
342 {
343   struct dot_progress *dp = progress;
344   int dot_bytes = opt.dot_bytes;
345   wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
346
347   log_set_flush (false);
348
349   dp->accumulated += howmuch;
350   for (; dp->accumulated >= dot_bytes; dp->accumulated -= dot_bytes)
351     {
352       if (dp->dots == 0)
353         logprintf (LOG_VERBOSE, "\n%6sK",
354                    number_to_static_string (dp->rows * ROW_BYTES / 1024));
355
356       if (dp->dots % opt.dot_spacing == 0)
357         logputs (LOG_VERBOSE, " ");
358       logputs (LOG_VERBOSE, ".");
359
360       ++dp->dots;
361       if (dp->dots >= opt.dots_in_line)
362         {
363           wgint row_qty = ROW_BYTES;
364           if (dp->rows == dp->initial_length / ROW_BYTES)
365             row_qty -= dp->initial_length % ROW_BYTES;
366
367           ++dp->rows;
368           dp->dots = 0;
369
370           print_row_stats (dp, dltime, false);
371         }
372     }
373
374   log_set_flush (true);
375 }
376
377 /* Dot-progress backend for progress_finish. */
378
379 static void
380 dot_finish (void *progress, double dltime)
381 {
382   struct dot_progress *dp = progress;
383   wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
384   int i;
385
386   log_set_flush (false);
387
388   if (dp->dots == 0)
389     logprintf (LOG_VERBOSE, "\n%6sK",
390                number_to_static_string (dp->rows * ROW_BYTES / 1024));
391   for (i = dp->dots; i < opt.dots_in_line; i++)
392     {
393       if (i % opt.dot_spacing == 0)
394         logputs (LOG_VERBOSE, " ");
395       logputs (LOG_VERBOSE, " ");
396     }
397
398   print_row_stats (dp, dltime, true);
399   logputs (LOG_VERBOSE, "\n\n");
400   log_set_flush (false);
401
402   xfree (dp);
403 }
404
405 /* This function interprets the progress "parameters".  For example,
406    if Wget is invoked with --progress=dot:mega, it will set the
407    "dot-style" to "mega".  Valid styles are default, binary, mega, and
408    giga.  */
409
410 static void
411 dot_set_params (const char *params)
412 {
413   if (!params || !*params)
414     params = opt.dot_style;
415
416   if (!params)
417     return;
418
419   /* We use this to set the retrieval style.  */
420   if (!strcasecmp (params, "default"))
421     {
422       /* Default style: 1K dots, 10 dots in a cluster, 50 dots in a
423          line.  */
424       opt.dot_bytes = 1024;
425       opt.dot_spacing = 10;
426       opt.dots_in_line = 50;
427     }
428   else if (!strcasecmp (params, "binary"))
429     {
430       /* "Binary" retrieval: 8K dots, 16 dots in a cluster, 48 dots
431          (384K) in a line.  */
432       opt.dot_bytes = 8192;
433       opt.dot_spacing = 16;
434       opt.dots_in_line = 48;
435     }
436   else if (!strcasecmp (params, "mega"))
437     {
438       /* "Mega" retrieval, for retrieving very long files; each dot is
439          64K, 8 dots in a cluster, 6 clusters (3M) in a line.  */
440       opt.dot_bytes = 65536L;
441       opt.dot_spacing = 8;
442       opt.dots_in_line = 48;
443     }
444   else if (!strcasecmp (params, "giga"))
445     {
446       /* "Giga" retrieval, for retrieving very very *very* long files;
447          each dot is 1M, 8 dots in a cluster, 4 clusters (32M) in a
448          line.  */
449       opt.dot_bytes = (1L << 20);
450       opt.dot_spacing = 8;
451       opt.dots_in_line = 32;
452     }
453   else
454     fprintf (stderr,
455              _("Invalid dot style specification `%s'; leaving unchanged.\n"),
456              params);
457 }
458 \f
459 /* "Thermometer" (bar) progress. */
460
461 /* Assumed screen width if we can't find the real value.  */
462 #define DEFAULT_SCREEN_WIDTH 80
463
464 /* Minimum screen width we'll try to work with.  If this is too small,
465    create_image will overflow the buffer.  */
466 #define MINIMUM_SCREEN_WIDTH 45
467
468 /* The last known screen width.  This can be updated by the code that
469    detects that SIGWINCH was received (but it's never updated from the
470    signal handler).  */
471 static int screen_width;
472
473 /* A flag that, when set, means SIGWINCH was received.  */
474 static volatile sig_atomic_t received_sigwinch;
475
476 /* Size of the download speed history ring. */
477 #define DLSPEED_HISTORY_SIZE 20
478
479 /* The minimum time length of a history sample.  By default, each
480    sample is at least 150ms long, which means that, over the course of
481    20 samples, "current" download speed spans at least 3s into the
482    past.  */
483 #define DLSPEED_SAMPLE_MIN 150
484
485 /* The time after which the download starts to be considered
486    "stalled", i.e. the current bandwidth is not printed and the recent
487    download speeds are scratched.  */
488 #define STALL_START_TIME 5000
489
490 struct bar_progress {
491   wgint initial_length;         /* how many bytes have been downloaded
492                                    previously. */
493   wgint total_length;           /* expected total byte count when the
494                                    download finishes */
495   wgint count;                  /* bytes downloaded so far */
496
497   double last_screen_update;    /* time of the last screen update,
498                                    measured since the beginning of
499                                    download. */
500
501   int width;                    /* screen width we're using at the
502                                    time the progress gauge was
503                                    created.  this is different from
504                                    the screen_width global variable in
505                                    that the latter can be changed by a
506                                    signal. */
507   char *buffer;                 /* buffer where the bar "image" is
508                                    stored. */
509   int tick;                     /* counter used for drawing the
510                                    progress bar where the total size
511                                    is not known. */
512
513   /* The following variables (kept in a struct for namespace reasons)
514      keep track of recent download speeds.  See bar_update() for
515      details.  */
516   struct bar_progress_hist {
517     int pos;
518     wgint times[DLSPEED_HISTORY_SIZE];
519     wgint bytes[DLSPEED_HISTORY_SIZE];
520
521     /* The sum of times and bytes respectively, maintained for
522        efficiency. */
523     wgint total_time;
524     wgint total_bytes;
525   } hist;
526
527   double recent_start;          /* timestamp of beginning of current
528                                    position. */
529   wgint recent_bytes;           /* bytes downloaded so far. */
530
531   bool stalled;                 /* set when no data arrives for longer
532                                    than STALL_START_TIME, then reset
533                                    when new data arrives. */
534
535   /* create_image() uses these to make sure that ETA information
536      doesn't flicker. */
537   double last_eta_time;         /* time of the last update to download
538                                    speed and ETA, measured since the
539                                    beginning of download. */
540   int last_eta_value;
541 };
542
543 static void create_image (struct bar_progress *, double, bool);
544 static void display_image (char *);
545
546 static void *
547 bar_create (wgint initial, wgint total)
548 {
549   struct bar_progress *bp = xnew0 (struct bar_progress);
550
551   /* In theory, our callers should take care of this pathological
552      case, but it can sometimes happen. */
553   if (initial > total)
554     total = initial;
555
556   bp->initial_length = initial;
557   bp->total_length   = total;
558
559   /* Initialize screen_width if this hasn't been done or if it might
560      have changed, as indicated by receiving SIGWINCH.  */
561   if (!screen_width || received_sigwinch)
562     {
563       screen_width = determine_screen_width ();
564       if (!screen_width)
565         screen_width = DEFAULT_SCREEN_WIDTH;
566       else if (screen_width < MINIMUM_SCREEN_WIDTH)
567         screen_width = MINIMUM_SCREEN_WIDTH;
568       received_sigwinch = 0;
569     }
570
571   /* - 1 because we don't want to use the last screen column. */
572   bp->width = screen_width - 1;
573   /* + 1 for the terminating zero. */
574   bp->buffer = xmalloc (bp->width + 1);
575
576   logputs (LOG_VERBOSE, "\n");
577
578   create_image (bp, 0, false);
579   display_image (bp->buffer);
580
581   return bp;
582 }
583
584 static void update_speed_ring (struct bar_progress *, wgint, double);
585
586 static void
587 bar_update (void *progress, wgint howmuch, double dltime)
588 {
589   struct bar_progress *bp = progress;
590   bool force_screen_update = false;
591
592   bp->count += howmuch;
593   if (bp->total_length > 0
594       && bp->count + bp->initial_length > bp->total_length)
595     /* We could be downloading more than total_length, e.g. when the
596        server sends an incorrect Content-Length header.  In that case,
597        adjust bp->total_length to the new reality, so that the code in
598        create_image() that depends on total size being smaller or
599        equal to the expected size doesn't abort.  */
600     bp->total_length = bp->initial_length + bp->count;
601
602   update_speed_ring (bp, howmuch, dltime);
603
604   /* If SIGWINCH (the window size change signal) been received,
605      determine the new screen size and update the screen.  */
606   if (received_sigwinch)
607     {
608       int old_width = screen_width;
609       screen_width = determine_screen_width ();
610       if (!screen_width)
611         screen_width = DEFAULT_SCREEN_WIDTH;
612       else if (screen_width < MINIMUM_SCREEN_WIDTH)
613         screen_width = MINIMUM_SCREEN_WIDTH;
614       if (screen_width != old_width)
615         {
616           bp->width = screen_width - 1;
617           bp->buffer = xrealloc (bp->buffer, bp->width + 1);
618           force_screen_update = true;
619         }
620       received_sigwinch = 0;
621     }
622
623   if (dltime - bp->last_screen_update < 200 && !force_screen_update)
624     /* Don't update more often than five times per second. */
625     return;
626
627   create_image (bp, dltime, false);
628   display_image (bp->buffer);
629   bp->last_screen_update = dltime;
630 }
631
632 static void
633 bar_finish (void *progress, double dltime)
634 {
635   struct bar_progress *bp = progress;
636
637   if (bp->total_length > 0
638       && bp->count + bp->initial_length > bp->total_length)
639     /* See bar_update() for explanation. */
640     bp->total_length = bp->initial_length + bp->count;
641
642   create_image (bp, dltime, true);
643   display_image (bp->buffer);
644
645   logputs (LOG_VERBOSE, "\n\n");
646
647   xfree (bp->buffer);
648   xfree (bp);
649 }
650
651 /* This code attempts to maintain the notion of a "current" download
652    speed, over the course of no less than 3s.  (Shorter intervals
653    produce very erratic results.)
654
655    To do so, it samples the speed in 150ms intervals and stores the
656    recorded samples in a FIFO history ring.  The ring stores no more
657    than 20 intervals, hence the history covers the period of at least
658    three seconds and at most 20 reads into the past.  This method
659    should produce reasonable results for downloads ranging from very
660    slow to very fast.
661
662    The idea is that for fast downloads, we get the speed over exactly
663    the last three seconds.  For slow downloads (where a network read
664    takes more than 150ms to complete), we get the speed over a larger
665    time period, as large as it takes to complete thirty reads.  This
666    is good because slow downloads tend to fluctuate more and a
667    3-second average would be too erratic.  */
668
669 static void
670 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
671 {
672   struct bar_progress_hist *hist = &bp->hist;
673   double recent_age = dltime - bp->recent_start;
674
675   /* Update the download count. */
676   bp->recent_bytes += howmuch;
677
678   /* For very small time intervals, we return after having updated the
679      "recent" download count.  When its age reaches or exceeds minimum
680      sample time, it will be recorded in the history ring.  */
681   if (recent_age < DLSPEED_SAMPLE_MIN)
682     return;
683
684   if (howmuch == 0)
685     {
686       /* If we're not downloading anything, we might be stalling,
687          i.e. not downloading anything for an extended period of time.
688          Since 0-reads do not enter the history ring, recent_age
689          effectively measures the time since last read.  */
690       if (recent_age >= STALL_START_TIME)
691         {
692           /* If we're stalling, reset the ring contents because it's
693              stale and because it will make bar_update stop printing
694              the (bogus) current bandwidth.  */
695           bp->stalled = true;
696           xzero (*hist);
697           bp->recent_bytes = 0;
698         }
699       return;
700     }
701
702   /* We now have a non-zero amount of to store to the speed ring.  */
703
704   /* If the stall status was acquired, reset it. */
705   if (bp->stalled)
706     {
707       bp->stalled = false;
708       /* "recent_age" includes the the entired stalled period, which
709          could be very long.  Don't update the speed ring with that
710          value because the current bandwidth would start too small.
711          Start with an arbitrary (but more reasonable) time value and
712          let it level out.  */
713       recent_age = 1000;
714     }
715
716   /* Store "recent" bytes and download time to history ring at the
717      position POS.  */
718
719   /* To correctly maintain the totals, first invalidate existing data
720      (least recent in time) at this position. */
721   hist->total_time  -= hist->times[hist->pos];
722   hist->total_bytes -= hist->bytes[hist->pos];
723
724   /* Now store the new data and update the totals. */
725   hist->times[hist->pos] = recent_age;
726   hist->bytes[hist->pos] = bp->recent_bytes;
727   hist->total_time  += recent_age;
728   hist->total_bytes += bp->recent_bytes;
729
730   /* Start a new "recent" period. */
731   bp->recent_start = dltime;
732   bp->recent_bytes = 0;
733
734   /* Advance the current ring position. */
735   if (++hist->pos == DLSPEED_HISTORY_SIZE)
736     hist->pos = 0;
737
738 #if 0
739   /* Sledgehammer check to verify that the totals are accurate. */
740   {
741     int i;
742     double sumt = 0, sumb = 0;
743     for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
744       {
745         sumt += hist->times[i];
746         sumb += hist->bytes[i];
747       }
748     assert (sumt == hist->total_time);
749     assert (sumb == hist->total_bytes);
750   }
751 #endif
752 }
753
754 #define APPEND_LITERAL(s) do {                  \
755   memcpy (p, s, sizeof (s) - 1);                \
756   p += sizeof (s) - 1;                          \
757 } while (0)
758
759 /* Use move_to_end (s) to get S to point the end of the string (the
760    terminating \0).  This is faster than s+=strlen(s), but some people
761    are confused when they see strchr (s, '\0') in the code.  */
762 #define move_to_end(s) s = strchr (s, '\0');
763
764 #ifndef MAX
765 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
766 #endif
767
768 static void
769 create_image (struct bar_progress *bp, double dl_total_time, bool done)
770 {
771   char *p = bp->buffer;
772   wgint size = bp->initial_length + bp->count;
773
774   const char *size_grouped = with_thousand_seps (size);
775   int size_grouped_len = strlen (size_grouped);
776
777   struct bar_progress_hist *hist = &bp->hist;
778
779   /* The progress bar should look like this:
780      xx% [=======>             ] nn,nnn 12.34K/s  eta 36m 51s
781
782      Calculate the geometry.  The idea is to assign as much room as
783      possible to the progress bar.  The other idea is to never let
784      things "jitter", i.e. pad elements that vary in size so that
785      their variance does not affect the placement of other elements.
786      It would be especially bad for the progress bar to be resized
787      randomly.
788
789      "xx% " or "100%"  - percentage               - 4 chars
790      "[]"              - progress bar decorations - 2 chars
791      " nnn,nnn,nnn"    - downloaded bytes         - 12 chars or very rarely more
792      " 1012.56K/s"     - dl rate                  - 11 chars
793      "  eta 36m 51s"   - ETA                      - 13 chars
794
795      "=====>..."       - progress bar             - the rest
796   */
797   int dlbytes_size = 1 + MAX (size_grouped_len, 11);
798   int progress_size = bp->width - (4 + 2 + dlbytes_size + 11 + 13);
799
800   if (progress_size < 5)
801     progress_size = 0;
802
803   /* "xx% " */
804   if (bp->total_length > 0)
805     {
806       int percentage = 100.0 * size / bp->total_length;
807       assert (percentage <= 100);
808
809       if (percentage < 100)
810         sprintf (p, "%2d%% ", percentage);
811       else
812         strcpy (p, "100%");
813       p += 4;
814     }
815   else
816     APPEND_LITERAL ("    ");
817
818   /* The progress bar: "[====>      ]" or "[++==>      ]". */
819   if (progress_size && bp->total_length > 0)
820     {
821       /* Size of the initial portion. */
822       int insz = (double)bp->initial_length / bp->total_length * progress_size;
823
824       /* Size of the downloaded portion. */
825       int dlsz = (double)size / bp->total_length * progress_size;
826
827       char *begin;
828       int i;
829
830       assert (dlsz <= progress_size);
831       assert (insz <= dlsz);
832
833       *p++ = '[';
834       begin = p;
835
836       /* Print the initial portion of the download with '+' chars, the
837          rest with '=' and one '>'.  */
838       for (i = 0; i < insz; i++)
839         *p++ = '+';
840       dlsz -= insz;
841       if (dlsz > 0)
842         {
843           for (i = 0; i < dlsz - 1; i++)
844             *p++ = '=';
845           *p++ = '>';
846         }
847
848       while (p - begin < progress_size)
849         *p++ = ' ';
850       *p++ = ']';
851     }
852   else if (progress_size)
853     {
854       /* If we can't draw a real progress bar, then at least show
855          *something* to the user.  */
856       int ind = bp->tick % (progress_size * 2 - 6);
857       int i, pos;
858
859       /* Make the star move in two directions. */
860       if (ind < progress_size - 2)
861         pos = ind + 1;
862       else
863         pos = progress_size - (ind - progress_size + 5);
864
865       *p++ = '[';
866       for (i = 0; i < progress_size; i++)
867         {
868           if      (i == pos - 1) *p++ = '<';
869           else if (i == pos    ) *p++ = '=';
870           else if (i == pos + 1) *p++ = '>';
871           else
872             *p++ = ' ';
873         }
874       *p++ = ']';
875
876       ++bp->tick;
877     }
878
879   /* " 234,567,890" */
880   sprintf (p, " %-11s", size_grouped);
881   move_to_end (p);
882
883   /* " 1012.45K/s" */
884   if (hist->total_time && hist->total_bytes)
885     {
886       static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" };
887       int units = 0;
888       /* Calculate the download speed using the history ring and
889          recent data that hasn't made it to the ring yet.  */
890       wgint dlquant = hist->total_bytes + bp->recent_bytes;
891       double dltime = hist->total_time + (dl_total_time - bp->recent_start);
892       double dlspeed = calc_rate (dlquant, dltime, &units);
893       sprintf (p, " %7.2f%s", dlspeed, short_units[units]);
894       move_to_end (p);
895     }
896   else
897     APPEND_LITERAL ("   --.--K/s");
898
899   if (!done)
900     {
901       /* "  eta ..m ..s"; wait for three seconds before displaying the ETA.
902          That's because the ETA value needs a while to become
903          reliable.  */
904       if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3000)
905         {
906           int eta;
907
908           /* Don't change the value of ETA more than approximately once
909              per second; doing so would cause flashing without providing
910              any value to the user. */
911           if (bp->total_length != size
912               && bp->last_eta_value != 0
913               && dl_total_time - bp->last_eta_time < 900)
914             eta = bp->last_eta_value;
915           else
916             {
917               /* Calculate ETA using the average download speed to predict
918                  the future speed.  If you want to use a speed averaged
919                  over a more recent period, replace dl_total_time with
920                  hist->total_time and bp->count with hist->total_bytes.
921                  I found that doing that results in a very jerky and
922                  ultimately unreliable ETA.  */
923               double time_sofar = (double) dl_total_time / 1000;
924               wgint bytes_remaining = bp->total_length - size;
925               eta = (int) (time_sofar * bytes_remaining / bp->count + 0.5);
926               bp->last_eta_value = eta;
927               bp->last_eta_time = dl_total_time;
928             }
929
930           /* Translation note: "ETA" is English-centric, but this must
931              be short, ideally 3 chars.  Abbreviate if necessary.  */
932           sprintf (p, _("  eta %s"), eta_to_human_short (eta, false));
933           move_to_end (p);
934         }
935       else if (bp->total_length > 0)
936         {
937           APPEND_LITERAL ("             ");
938         }
939     }
940   else
941     {
942       /* When the download is done, print the elapsed time.  */
943       double secs = dl_total_time / 1000;
944       /* Note to translators: this should not take up more room than
945          available here.  Abbreviate if necessary.  */
946       strcpy (p, _("   in "));
947       move_to_end (p);          /* not p+=6, think translations! */
948       if (secs >= 10)
949         strcpy (p, eta_to_human_short ((int) (secs + 0.5), false));
950       else
951         sprintf (p, "%ss", print_decimal (secs));
952       move_to_end (p);
953     }
954
955   assert (p - bp->buffer <= bp->width);
956
957   while (p < bp->buffer + bp->width)
958     *p++ = ' ';
959   *p = '\0';
960 }
961
962 /* Print the contents of the buffer as a one-line ASCII "image" so
963    that it can be overwritten next time.  */
964
965 static void
966 display_image (char *buf)
967 {
968   bool old = log_set_save_context (false);
969   logputs (LOG_VERBOSE, "\r");
970   logputs (LOG_VERBOSE, buf);
971   log_set_save_context (old);
972 }
973
974 static void
975 bar_set_params (const char *params)
976 {
977   char *term = getenv ("TERM");
978
979   if (params
980       && 0 == strcmp (params, "force"))
981     current_impl_locked = 1;
982
983   if ((opt.lfilename
984 #ifdef HAVE_ISATTY
985        /* The progress bar doesn't make sense if the output is not a
986           TTY -- when logging to file, it is better to review the
987           dots.  */
988        || !isatty (fileno (stderr))
989 #endif
990        /* Normally we don't depend on terminal type because the
991           progress bar only uses ^M to move the cursor to the
992           beginning of line, which works even on dumb terminals.  But
993           Jamie Zawinski reports that ^M and ^H tricks don't work in
994           Emacs shell buffers, and only make a mess.  */
995        || (term && 0 == strcmp (term, "emacs"))
996        )
997       && !current_impl_locked)
998     {
999       /* We're not printing to a TTY, so revert to the fallback
1000          display.  #### We're recursively calling
1001          set_progress_implementation here, which is slightly kludgy.
1002          It would be nicer if we provided that function a return value
1003          indicating a failure of some sort.  */
1004       set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1005       return;
1006     }
1007 }
1008
1009 #ifdef SIGWINCH
1010 void
1011 progress_handle_sigwinch (int sig)
1012 {
1013   received_sigwinch = 1;
1014   signal (SIGWINCH, progress_handle_sigwinch);
1015 }
1016 #endif
1017
1018 /* Provide a short human-readable rendition of the ETA.  This is like
1019    secs_to_human_time in main.c, except the output doesn't include
1020    fractions (which would look silly in by nature imprecise ETA) and
1021    takes less room.  If the time is measured in hours, hours and
1022    minutes (but not seconds) are shown; if measured in days, then days
1023    and hours are shown.  This ensures brevity while still displaying
1024    as much as possible.
1025
1026    If CONDENSED is true, the separator between minutes and seconds
1027    (and hours and minutes, etc.) is not included, shortening the
1028    display by one additional character.  This is used for dot
1029    progress.
1030
1031    The display never occupies more than 7 characters of screen
1032    space.  */
1033
1034 static const char *
1035 eta_to_human_short (int secs, bool condensed)
1036 {
1037   static char buf[10];          /* 8 should be enough, but just in case */
1038   static int last = -1;
1039   const char *space = condensed ? "" : " ";
1040
1041   /* Trivial optimization.  create_image can call us every 200 msecs
1042      (see bar_update) for fast downloads, but ETA will only change
1043      once per 900 msecs.  */
1044   if (secs == last)
1045     return buf;
1046   last = secs;
1047
1048   if (secs < 100)
1049     sprintf (buf, "%ds", secs);
1050   else if (secs < 100 * 60)
1051     sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1052   else if (secs < 100 * 3600)
1053     sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1054   else if (secs < 100 * 86400)
1055     sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 60);
1056   else
1057     /* even (2^31-1)/86400 doesn't overflow BUF. */
1058     sprintf (buf, "%dd", secs / 86400);
1059
1060   return buf;
1061 }