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