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