]> sjero.net Git - wget/blob - src/progress.c
Fix build when libpsl is not available
[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) (const char *, wgint, wgint);
51   void (*update) (void *, wgint, double);
52   void (*draw) (void *);
53   void (*finish) (void *, double);
54   void (*set_params) (char *);
55 };
56
57 /* Necessary forward declarations. */
58
59 static void *dot_create (const char *, 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 (char *);
64
65 static void *bar_create (const char *, 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 (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   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 (const char *f_download, 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 (f_download, 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 _GL_UNUSED)
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 (const char *f_download _GL_UNUSED, 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_PROGRESS, _("\n%*s[ skipping %sK ]"),
246                      2 + skipped_k_len, "",
247                      number_to_static_string (skipped_k));
248         }
249
250       logprintf (LOG_PROGRESS, "\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_PROGRESS, " ");
256           logputs (LOG_PROGRESS, ",");
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_PROGRESS, "%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_PROGRESS, " %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_PROGRESS, " %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_PROGRESS, "=%s",
340                    eta_to_human_short ((int) (dltime + 0.5), true));
341       else
342         logprintf (LOG_PROGRESS, "=%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_PROGRESS, "\n%6sK",
369                    number_to_static_string (dp->rows * ROW_BYTES / 1024));
370
371       if (dp->dots % opt.dot_spacing == 0)
372         logputs (LOG_PROGRESS, " ");
373       logputs (LOG_PROGRESS, ".");
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_PROGRESS, "\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_PROGRESS, " ");
406       logputs (LOG_PROGRESS, " ");
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 (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   const char *f_download;       /* Filename of the downloaded file */
511   wgint initial_length;         /* how many bytes have been downloaded
512                                    previously. */
513   wgint total_length;           /* expected total byte count when the
514                                    download finishes */
515   wgint count;                  /* bytes downloaded so far */
516
517   double last_screen_update;    /* time of the last screen update,
518                                    measured since the beginning of
519                                    download. */
520
521   double dltime;                /* download time so far */
522   int width;                    /* screen width we're using at the
523                                    time the progress gauge was
524                                    created.  this is different from
525                                    the screen_width global variable in
526                                    that the latter can be changed by a
527                                    signal. */
528   char *buffer;                 /* buffer where the bar "image" is
529                                    stored. */
530   int tick;                     /* counter used for drawing the
531                                    progress bar where the total size
532                                    is not known. */
533
534   /* The following variables (kept in a struct for namespace reasons)
535      keep track of recent download speeds.  See bar_update() for
536      details.  */
537   struct bar_progress_hist {
538     int pos;
539     double times[DLSPEED_HISTORY_SIZE];
540     wgint bytes[DLSPEED_HISTORY_SIZE];
541
542     /* The sum of times and bytes respectively, maintained for
543        efficiency. */
544     double total_time;
545     wgint total_bytes;
546   } hist;
547
548   double recent_start;          /* timestamp of beginning of current
549                                    position. */
550   wgint recent_bytes;           /* bytes downloaded so far. */
551
552   bool stalled;                 /* set when no data arrives for longer
553                                    than STALL_START_TIME, then reset
554                                    when new data arrives. */
555
556   /* create_image() uses these to make sure that ETA information
557      doesn't flicker. */
558   double last_eta_time;         /* time of the last update to download
559                                    speed and ETA, measured since the
560                                    beginning of download. */
561   int last_eta_value;
562 };
563
564 static void create_image (struct bar_progress *, double, bool);
565 static void display_image (char *);
566
567 static void *
568 bar_create (const char *f_download, wgint initial, wgint total)
569 {
570   struct bar_progress *bp = xnew0 (struct bar_progress);
571
572   /* In theory, our callers should take care of this pathological
573      case, but it can sometimes happen. */
574   if (initial > total)
575     total = initial;
576
577   bp->initial_length = initial;
578   bp->total_length   = total;
579   bp->f_download     = f_download;
580
581   /* Initialize screen_width if this hasn't been done or if it might
582      have changed, as indicated by receiving SIGWINCH.  */
583   if (!screen_width || received_sigwinch)
584     {
585       screen_width = determine_screen_width ();
586       if (!screen_width)
587         screen_width = DEFAULT_SCREEN_WIDTH;
588       else if (screen_width < MINIMUM_SCREEN_WIDTH)
589         screen_width = MINIMUM_SCREEN_WIDTH;
590       received_sigwinch = 0;
591     }
592
593   /* - 1 because we don't want to use the last screen column. */
594   bp->width = screen_width - 1;
595   /* + enough space for the terminating zero, and hopefully enough room
596    * for multibyte characters. */
597   bp->buffer = xmalloc (bp->width + 100);
598
599   logputs (LOG_VERBOSE, "\n");
600
601   create_image (bp, 0, false);
602   display_image (bp->buffer);
603
604   return bp;
605 }
606
607 static void update_speed_ring (struct bar_progress *, wgint, double);
608
609 static void
610 bar_update (void *progress, wgint howmuch, double dltime)
611 {
612   struct bar_progress *bp = progress;
613
614   bp->dltime = dltime;
615   bp->count += howmuch;
616   if (bp->total_length > 0
617       && bp->count + bp->initial_length > bp->total_length)
618     /* We could be downloading more than total_length, e.g. when the
619        server sends an incorrect Content-Length header.  In that case,
620        adjust bp->total_length to the new reality, so that the code in
621        create_image() that depends on total size being smaller or
622        equal to the expected size doesn't abort.  */
623     bp->total_length = bp->initial_length + bp->count;
624
625   update_speed_ring (bp, howmuch, dltime);
626 }
627
628 static void
629 bar_draw (void *progress)
630 {
631   bool force_screen_update = false;
632   struct bar_progress *bp = progress;
633
634   /* If SIGWINCH (the window size change signal) been received,
635      determine the new screen size and update the screen.  */
636   if (received_sigwinch)
637     {
638       int old_width = screen_width;
639       screen_width = determine_screen_width ();
640       if (!screen_width)
641         screen_width = DEFAULT_SCREEN_WIDTH;
642       else if (screen_width < MINIMUM_SCREEN_WIDTH)
643         screen_width = MINIMUM_SCREEN_WIDTH;
644       if (screen_width != old_width)
645         {
646           bp->width = screen_width - 1;
647           bp->buffer = xrealloc (bp->buffer, bp->width + 100);
648           force_screen_update = true;
649         }
650       received_sigwinch = 0;
651     }
652
653   if (bp->dltime - bp->last_screen_update < REFRESH_INTERVAL && !force_screen_update)
654     /* Don't update more often than five times per second. */
655     return;
656
657   create_image (bp, bp->dltime, false);
658   display_image (bp->buffer);
659   bp->last_screen_update = bp->dltime;
660 }
661
662 static void
663 bar_finish (void *progress, double dltime)
664 {
665   struct bar_progress *bp = progress;
666
667   if (bp->total_length > 0
668       && bp->count + bp->initial_length > bp->total_length)
669     /* See bar_update() for explanation. */
670     bp->total_length = bp->initial_length + bp->count;
671
672   create_image (bp, dltime, true);
673   display_image (bp->buffer);
674
675   logputs (LOG_VERBOSE, "\n");
676   logputs (LOG_PROGRESS, "\n");
677
678   xfree (bp->buffer);
679   xfree (bp);
680 }
681
682 /* This code attempts to maintain the notion of a "current" download
683    speed, over the course of no less than 3s.  (Shorter intervals
684    produce very erratic results.)
685
686    To do so, it samples the speed in 150ms intervals and stores the
687    recorded samples in a FIFO history ring.  The ring stores no more
688    than 20 intervals, hence the history covers the period of at least
689    three seconds and at most 20 reads into the past.  This method
690    should produce reasonable results for downloads ranging from very
691    slow to very fast.
692
693    The idea is that for fast downloads, we get the speed over exactly
694    the last three seconds.  For slow downloads (where a network read
695    takes more than 150ms to complete), we get the speed over a larger
696    time period, as large as it takes to complete thirty reads.  This
697    is good because slow downloads tend to fluctuate more and a
698    3-second average would be too erratic.  */
699
700 static void
701 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
702 {
703   struct bar_progress_hist *hist = &bp->hist;
704   double recent_age = dltime - bp->recent_start;
705
706   /* Update the download count. */
707   bp->recent_bytes += howmuch;
708
709   /* For very small time intervals, we return after having updated the
710      "recent" download count.  When its age reaches or exceeds minimum
711      sample time, it will be recorded in the history ring.  */
712   if (recent_age < DLSPEED_SAMPLE_MIN)
713     return;
714
715   if (howmuch == 0)
716     {
717       /* If we're not downloading anything, we might be stalling,
718          i.e. not downloading anything for an extended period of time.
719          Since 0-reads do not enter the history ring, recent_age
720          effectively measures the time since last read.  */
721       if (recent_age >= STALL_START_TIME)
722         {
723           /* If we're stalling, reset the ring contents because it's
724              stale and because it will make bar_update stop printing
725              the (bogus) current bandwidth.  */
726           bp->stalled = true;
727           xzero (*hist);
728           bp->recent_bytes = 0;
729         }
730       return;
731     }
732
733   /* We now have a non-zero amount of to store to the speed ring.  */
734
735   /* If the stall status was acquired, reset it. */
736   if (bp->stalled)
737     {
738       bp->stalled = false;
739       /* "recent_age" includes the entired stalled period, which
740          could be very long.  Don't update the speed ring with that
741          value because the current bandwidth would start too small.
742          Start with an arbitrary (but more reasonable) time value and
743          let it level out.  */
744       recent_age = 1;
745     }
746
747   /* Store "recent" bytes and download time to history ring at the
748      position POS.  */
749
750   /* To correctly maintain the totals, first invalidate existing data
751      (least recent in time) at this position. */
752   hist->total_time  -= hist->times[hist->pos];
753   hist->total_bytes -= hist->bytes[hist->pos];
754
755   /* Now store the new data and update the totals. */
756   hist->times[hist->pos] = recent_age;
757   hist->bytes[hist->pos] = bp->recent_bytes;
758   hist->total_time  += recent_age;
759   hist->total_bytes += bp->recent_bytes;
760
761   /* Start a new "recent" period. */
762   bp->recent_start = dltime;
763   bp->recent_bytes = 0;
764
765   /* Advance the current ring position. */
766   if (++hist->pos == DLSPEED_HISTORY_SIZE)
767     hist->pos = 0;
768
769 #if 0
770   /* Sledgehammer check to verify that the totals are accurate. */
771   {
772     int i;
773     double sumt = 0, sumb = 0;
774     for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
775       {
776         sumt += hist->times[i];
777         sumb += hist->bytes[i];
778       }
779     assert (sumb == hist->total_bytes);
780     /* We can't use assert(sumt==hist->total_time) because some
781        precision is lost by adding and subtracting floating-point
782        numbers.  But during a download this precision should not be
783        detectable, i.e. no larger than 1ns.  */
784     double diff = sumt - hist->total_time;
785     if (diff < 0) diff = -diff;
786     assert (diff < 1e-9);
787   }
788 #endif
789 }
790
791 #if USE_NLS_PROGRESS_BAR
792 static int
793 count_cols (const char *mbs)
794 {
795   wchar_t wc;
796   int     bytes;
797   int     remaining = strlen(mbs);
798   int     cols = 0;
799   int     wccols;
800
801   while (*mbs != '\0')
802     {
803       bytes = mbtowc (&wc, mbs, remaining);
804       assert (bytes != 0);  /* Only happens when *mbs == '\0' */
805       if (bytes == -1)
806         {
807           /* Invalid sequence. We'll just have to fudge it. */
808           return cols + remaining;
809         }
810       mbs += bytes;
811       remaining -= bytes;
812       wccols = wcwidth(wc);
813       cols += (wccols == -1? 1 : wccols);
814     }
815   return cols;
816 }
817 #else
818 # define count_cols(mbs) ((int)(strlen(mbs)))
819 #endif
820
821 static const char *
822 get_eta (int *bcd)
823 {
824   /* TRANSLATORS: "ETA" is English-centric, but this must
825      be short, ideally 3 chars.  Abbreviate if necessary.  */
826   static const char eta_str[] = N_("   eta %s");
827   static const char *eta_trans;
828   static int bytes_cols_diff;
829   if (eta_trans == NULL)
830     {
831       int nbytes;
832       int ncols;
833
834 #if USE_NLS_PROGRESS_BAR
835       eta_trans = _(eta_str);
836 #else
837       eta_trans = eta_str;
838 #endif
839
840       /* Determine the number of bytes used in the translated string,
841        * versus the number of columns used. This is to figure out how
842        * many spaces to add at the end to pad to the full line width.
843        *
844        * We'll store the difference between the number of bytes and
845        * number of columns, so that removing this from the string length
846        * will reveal the total number of columns in the progress bar. */
847       nbytes = strlen (eta_trans);
848       ncols = count_cols (eta_trans);
849       bytes_cols_diff = nbytes - ncols;
850     }
851
852   if (bcd != NULL)
853     *bcd = bytes_cols_diff;
854
855   return eta_trans;
856 }
857
858 #define APPEND_LITERAL(s) do {                  \
859   memcpy (p, s, sizeof (s) - 1);                \
860   p += sizeof (s) - 1;                          \
861 } while (0)
862
863 /* Use move_to_end (s) to get S to point the end of the string (the
864    terminating \0).  This is faster than s+=strlen(s), but some people
865    are confused when they see strchr (s, '\0') in the code.  */
866 #define move_to_end(s) s = strchr (s, '\0');
867
868 #ifndef MAX
869 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
870 #endif
871 #ifndef MIN
872 # define MIN(a, b) ((a) <= (b) ? (a) : (b))
873 #endif
874
875 static void
876 create_image (struct bar_progress *bp, double dl_total_time, bool done)
877 {
878   const int MAX_FILENAME_LEN = bp->width / 4;
879   char *p = bp->buffer;
880   wgint size = bp->initial_length + bp->count;
881
882   const char *size_grouped = with_thousand_seps (size);
883   int size_grouped_len = count_cols (size_grouped);
884   /* Difference between num cols and num bytes: */
885   int size_grouped_diff = strlen (size_grouped) - size_grouped_len;
886   int size_grouped_pad; /* Used to pad the field width for size_grouped. */
887
888   struct bar_progress_hist *hist = &bp->hist;
889   int orig_filename_len = strlen (bp->f_download);
890
891   /* The progress bar should look like this:
892      file xx% [=======>             ] nnn.nnK 12.34KB/s  eta 36m 51s
893
894      Calculate the geometry.  The idea is to assign as much room as
895      possible to the progress bar.  The other idea is to never let
896      things "jitter", i.e. pad elements that vary in size so that
897      their variance does not affect the placement of other elements.
898      It would be especially bad for the progress bar to be resized
899      randomly.
900
901      "file "           - Downloaded filename      - MAX_FILENAME_LEN chars + 1
902      "xx% " or "100%"  - percentage               - 4 chars
903      "[]"              - progress bar decorations - 2 chars
904      " nnn.nnK"        - downloaded bytes         - 7 chars + 1
905      " 12.5KB/s"       - download rate            - 8 chars + 1
906      "  eta 36m 51s"   - ETA                      - 14 chars
907
908      "=====>..."       - progress bar             - the rest
909   */
910
911 #define PROGRESS_FILENAME_LEN  MAX_FILENAME_LEN + 1
912 #define PROGRESS_PERCENT_LEN   4
913 #define PROGRESS_DECORAT_LEN   2
914 #define PROGRESS_FILESIZE_LEN  7 + 1
915 #define PROGRESS_DWNLOAD_RATE  8 + 1
916 #define PROGRESS_ETA_LEN       14
917
918   int progress_size = bp->width - (PROGRESS_FILENAME_LEN + PROGRESS_PERCENT_LEN +
919                                    PROGRESS_DECORAT_LEN + PROGRESS_FILESIZE_LEN +
920                                    PROGRESS_DWNLOAD_RATE + PROGRESS_ETA_LEN);
921
922   /* The difference between the number of bytes used,
923      and the number of columns used. */
924   int bytes_cols_diff = 0;
925
926   if (progress_size < 5)
927     progress_size = 0;
928
929   if (orig_filename_len <= MAX_FILENAME_LEN)
930     {
931       int padding = MAX_FILENAME_LEN - orig_filename_len;
932       sprintf (p, "%s ", bp->f_download);
933       p += orig_filename_len + 1;
934       for (;padding;padding--)
935         *p++ = ' ';
936     }
937   else
938     {
939       int offset;
940
941       if (((orig_filename_len > MAX_FILENAME_LEN) && !opt.noscroll) && !done)
942         offset = ((int) bp->tick) % (orig_filename_len - MAX_FILENAME_LEN);
943       else
944         offset = 0;
945       memcpy (p, bp->f_download + offset, MAX_FILENAME_LEN);
946       p += MAX_FILENAME_LEN;
947       *p++ = ' ';
948     }
949
950   /* "xx% " */
951   if (bp->total_length > 0)
952     {
953       int percentage = 100.0 * size / bp->total_length;
954       assert (percentage <= 100);
955
956       if (percentage < 100)
957         sprintf (p, "%2d%% ", percentage);
958       else
959         strcpy (p, "100%");
960       p += 4;
961     }
962   else
963     APPEND_LITERAL ("    ");
964
965   /* The progress bar: "[====>      ]" or "[++==>      ]". */
966   if (progress_size && bp->total_length > 0)
967     {
968       /* Size of the initial portion. */
969       int insz = (double)bp->initial_length / bp->total_length * progress_size;
970
971       /* Size of the downloaded portion. */
972       int dlsz = (double)size / bp->total_length * progress_size;
973
974       char *begin;
975       int i;
976
977       assert (dlsz <= progress_size);
978       assert (insz <= dlsz);
979
980       *p++ = '[';
981       begin = p;
982
983       /* Print the initial portion of the download with '+' chars, the
984          rest with '=' and one '>'.  */
985       for (i = 0; i < insz; i++)
986         *p++ = '+';
987       dlsz -= insz;
988       if (dlsz > 0)
989         {
990           for (i = 0; i < dlsz - 1; i++)
991             *p++ = '=';
992           *p++ = '>';
993         }
994
995       while (p - begin < progress_size)
996         *p++ = ' ';
997       *p++ = ']';
998     }
999   else if (progress_size)
1000     {
1001       /* If we can't draw a real progress bar, then at least show
1002          *something* to the user.  */
1003       int ind = bp->tick % (progress_size * 2 - 6);
1004       int i, pos;
1005
1006       /* Make the star move in two directions. */
1007       if (ind < progress_size - 2)
1008         pos = ind + 1;
1009       else
1010         pos = progress_size - (ind - progress_size + 5);
1011
1012       *p++ = '[';
1013       for (i = 0; i < progress_size; i++)
1014         {
1015           if      (i == pos - 1) *p++ = '<';
1016           else if (i == pos    ) *p++ = '=';
1017           else if (i == pos + 1) *p++ = '>';
1018           else
1019             *p++ = ' ';
1020         }
1021       *p++ = ']';
1022
1023     }
1024  ++bp->tick;
1025
1026   /* " 234.56M" */
1027   const char * down_size = human_readable (size, 1000, 2);
1028   int cols_diff = 7 - count_cols (down_size);
1029   while (cols_diff > 0)
1030   {
1031     *p++=' ';
1032     cols_diff--;
1033   }
1034   sprintf (p, " %s", down_size);
1035   move_to_end (p);
1036   /* Pad with spaces to 7 chars for the size_grouped field;
1037    * couldn't use the field width specifier in sprintf, because
1038    * it counts in bytes, not characters. */
1039   for (size_grouped_pad = PROGRESS_FILESIZE_LEN - 7;
1040        size_grouped_pad > 0;
1041        --size_grouped_pad)
1042     {
1043       *p++ = ' ';
1044     }
1045
1046   /* " 12.52Kb/s or 12.52KB/s" */
1047   if (hist->total_time > 0 && hist->total_bytes)
1048     {
1049       static const char *short_units[] = { " B/s", "KB/s", "MB/s", "GB/s" };
1050       static const char *short_units_bits[] = { " b/s", "Kb/s", "Mb/s", "Gb/s" };
1051       int units = 0;
1052       /* Calculate the download speed using the history ring and
1053          recent data that hasn't made it to the ring yet.  */
1054       wgint dlquant = hist->total_bytes + bp->recent_bytes;
1055       double dltime = hist->total_time + (dl_total_time - bp->recent_start);
1056       double dlspeed = calc_rate (dlquant, dltime, &units);
1057       sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
1058                dlspeed,  !opt.report_bps ? short_units[units] : short_units_bits[units]);
1059       move_to_end (p);
1060     }
1061   else
1062     APPEND_LITERAL (" --.-KB/s");
1063
1064   if (!done)
1065     {
1066       /* "  eta ..m ..s"; wait for three seconds before displaying the ETA.
1067          That's because the ETA value needs a while to become
1068          reliable.  */
1069       if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
1070         {
1071           int eta;
1072
1073           /* Don't change the value of ETA more than approximately once
1074              per second; doing so would cause flashing without providing
1075              any value to the user. */
1076           if (bp->total_length != size
1077               && bp->last_eta_value != 0
1078               && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
1079             eta = bp->last_eta_value;
1080           else
1081             {
1082               /* Calculate ETA using the average download speed to predict
1083                  the future speed.  If you want to use a speed averaged
1084                  over a more recent period, replace dl_total_time with
1085                  hist->total_time and bp->count with hist->total_bytes.
1086                  I found that doing that results in a very jerky and
1087                  ultimately unreliable ETA.  */
1088               wgint bytes_remaining = bp->total_length - size;
1089               double eta_ = dl_total_time * bytes_remaining / bp->count;
1090               if (eta_ >= INT_MAX - 1)
1091                 goto skip_eta;
1092               eta = (int) (eta_ + 0.5);
1093               bp->last_eta_value = eta;
1094               bp->last_eta_time = dl_total_time;
1095             }
1096
1097           sprintf (p, get_eta(&bytes_cols_diff),
1098                    eta_to_human_short (eta, false));
1099           move_to_end (p);
1100         }
1101       else if (bp->total_length > 0)
1102         {
1103         skip_eta:
1104           APPEND_LITERAL ("             ");
1105         }
1106     }
1107   else
1108     {
1109       /* When the download is done, print the elapsed time.  */
1110       int nbytes;
1111       int ncols;
1112
1113       /* Note to translators: this should not take up more room than
1114          available here.  Abbreviate if necessary.  */
1115       strcpy (p, _("   in "));
1116       nbytes = strlen (p);
1117       ncols  = count_cols (p);
1118       bytes_cols_diff = nbytes - ncols;
1119       p += nbytes;
1120       if (dl_total_time >= 10)
1121         strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
1122       else
1123         sprintf (p, "%ss", print_decimal (dl_total_time));
1124       move_to_end (p);
1125     }
1126
1127   while (p - bp->buffer - bytes_cols_diff - size_grouped_diff < bp->width)
1128     *p++ = ' ';
1129   *p = '\0';
1130 }
1131
1132 /* Print the contents of the buffer as a one-line ASCII "image" so
1133    that it can be overwritten next time.  */
1134
1135 static void
1136 display_image (char *buf)
1137 {
1138   bool old = log_set_save_context (false);
1139   logputs (LOG_PROGRESS, "\r");
1140   logputs (LOG_PROGRESS, buf);
1141   log_set_save_context (old);
1142 }
1143
1144 static void
1145 bar_set_params (char *params)
1146 {
1147   char *term = getenv ("TERM");
1148
1149   if (params)
1150     {
1151       char *param = strtok (params, ":");
1152       do
1153         {
1154           if (0 == strcmp (param, "force"))
1155             current_impl_locked = 1;
1156           else if (0 == strcmp (param, "noscroll"))
1157             opt.noscroll = true;
1158         } while ((param = strtok (NULL, ":")) != NULL);
1159     }
1160
1161   if ((opt.lfilename
1162 #ifdef HAVE_ISATTY
1163        /* The progress bar doesn't make sense if the output is not a
1164           TTY -- when logging to file, it is better to review the
1165           dots.  */
1166        || !isatty (fileno (stderr))
1167 #endif
1168        /* Normally we don't depend on terminal type because the
1169           progress bar only uses ^M to move the cursor to the
1170           beginning of line, which works even on dumb terminals.  But
1171           Jamie Zawinski reports that ^M and ^H tricks don't work in
1172           Emacs shell buffers, and only make a mess.  */
1173        || (term && 0 == strcmp (term, "emacs"))
1174        )
1175       && !current_impl_locked)
1176     {
1177       /* We're not printing to a TTY, so revert to the fallback
1178          display.  #### We're recursively calling
1179          set_progress_implementation here, which is slightly kludgy.
1180          It would be nicer if we provided that function a return value
1181          indicating a failure of some sort.  */
1182       set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1183       return;
1184     }
1185 }
1186
1187 #ifdef SIGWINCH
1188 void
1189 progress_handle_sigwinch (int sig _GL_UNUSED)
1190 {
1191   received_sigwinch = 1;
1192   signal (SIGWINCH, progress_handle_sigwinch);
1193 }
1194 #endif
1195
1196 /* Provide a short human-readable rendition of the ETA.  This is like
1197    secs_to_human_time in main.c, except the output doesn't include
1198    fractions (which would look silly in by nature imprecise ETA) and
1199    takes less room.  If the time is measured in hours, hours and
1200    minutes (but not seconds) are shown; if measured in days, then days
1201    and hours are shown.  This ensures brevity while still displaying
1202    as much as possible.
1203
1204    If CONDENSED is true, the separator between minutes and seconds
1205    (and hours and minutes, etc.) is not included, shortening the
1206    display by one additional character.  This is used for dot
1207    progress.
1208
1209    The display never occupies more than 7 characters of screen
1210    space.  */
1211
1212 static const char *
1213 eta_to_human_short (int secs, bool condensed)
1214 {
1215   static char buf[10];          /* 8 should be enough, but just in case */
1216   static int last = -1;
1217   const char *space = condensed ? "" : " ";
1218
1219   /* Trivial optimization.  create_image can call us every 200 msecs
1220      (see bar_update) for fast downloads, but ETA will only change
1221      once per 900 msecs.  */
1222   if (secs == last)
1223     return buf;
1224   last = secs;
1225
1226   if (secs < 100)
1227     sprintf (buf, "%ds", secs);
1228   else if (secs < 100 * 60)
1229     sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1230   else if (secs < 48 * 3600)
1231     sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1232   else if (secs < 100 * 86400)
1233     sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 24);
1234   else
1235     /* even (2^31-1)/86400 doesn't overflow BUF. */
1236     sprintf (buf, "%dd", secs / 86400);
1237
1238   return buf;
1239 }