]> sjero.net Git - wget/blob - src/progress.c
b1d509504c3889ea991ce4432273eeb5ecc6efad
[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) (const 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 (const 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 (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 (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)
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_PROGRESS, "\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   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 / 3;
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   int filename_len = MIN (orig_filename_len, MAX_FILENAME_LEN);
891
892   /* The progress bar should look like this:
893      file xx% [=======>             ] nn,nnn 12.34KB/s  eta 36m 51s
894
895      Calculate the geometry.  The idea is to assign as much room as
896      possible to the progress bar.  The other idea is to never let
897      things "jitter", i.e. pad elements that vary in size so that
898      their variance does not affect the placement of other elements.
899      It would be especially bad for the progress bar to be resized
900      randomly.
901
902      "file "           - Downloaded filename      - MAX MAX_FILENAME_LEN chars + 1
903      "xx% " or "100%"  - percentage               - 4 chars
904      "[]"              - progress bar decorations - 2 chars
905      " nnn,nnn,nnn"    - downloaded bytes         - 12 chars or very rarely more
906      " 12.5KB/s"       - download rate            - 9 chars
907      "  eta 36m 51s"   - ETA                      - 14 chars
908
909      "=====>..."       - progress bar             - the rest
910   */
911   int dlbytes_size = 1 + MAX (size_grouped_len, 11);
912   int progress_size = bp->width - (filename_len + 1 + 4 + 2 + dlbytes_size + 8 + 14);
913
914   /* The difference between the number of bytes used,
915      and the number of columns used. */
916   int bytes_cols_diff = 0;
917
918   if (progress_size < 5)
919     progress_size = 0;
920
921   if (orig_filename_len <= MAX_FILENAME_LEN)
922     {
923       sprintf (p, "%s ", bp->f_download);
924       p += filename_len + 1;
925     }
926   else
927     {
928       int offset;
929
930       if (orig_filename_len > MAX_FILENAME_LEN)
931         offset = ((int) bp->tick) % (orig_filename_len - MAX_FILENAME_LEN);
932       else
933         offset = 0;
934       *p++ = ' ';
935       memcpy (p, bp->f_download + offset, MAX_FILENAME_LEN);
936       p += MAX_FILENAME_LEN;
937       *p++ = ' ';
938     }
939
940   /* "xx% " */
941   if (bp->total_length > 0)
942     {
943       int percentage = 100.0 * size / bp->total_length;
944       assert (percentage <= 100);
945
946       if (percentage < 100)
947         sprintf (p, "%2d%% ", percentage);
948       else
949         strcpy (p, "100%");
950       p += 4;
951     }
952   else
953     APPEND_LITERAL ("    ");
954
955   /* The progress bar: "[====>      ]" or "[++==>      ]". */
956   if (progress_size && bp->total_length > 0)
957     {
958       /* Size of the initial portion. */
959       int insz = (double)bp->initial_length / bp->total_length * progress_size;
960
961       /* Size of the downloaded portion. */
962       int dlsz = (double)size / bp->total_length * progress_size;
963
964       char *begin;
965       int i;
966
967       assert (dlsz <= progress_size);
968       assert (insz <= dlsz);
969
970       *p++ = '[';
971       begin = p;
972
973       /* Print the initial portion of the download with '+' chars, the
974          rest with '=' and one '>'.  */
975       for (i = 0; i < insz; i++)
976         *p++ = '+';
977       dlsz -= insz;
978       if (dlsz > 0)
979         {
980           for (i = 0; i < dlsz - 1; i++)
981             *p++ = '=';
982           *p++ = '>';
983         }
984
985       while (p - begin < progress_size)
986         *p++ = ' ';
987       *p++ = ']';
988     }
989   else if (progress_size)
990     {
991       /* If we can't draw a real progress bar, then at least show
992          *something* to the user.  */
993       int ind = bp->tick % (progress_size * 2 - 6);
994       int i, pos;
995
996       /* Make the star move in two directions. */
997       if (ind < progress_size - 2)
998         pos = ind + 1;
999       else
1000         pos = progress_size - (ind - progress_size + 5);
1001
1002       *p++ = '[';
1003       for (i = 0; i < progress_size; i++)
1004         {
1005           if      (i == pos - 1) *p++ = '<';
1006           else if (i == pos    ) *p++ = '=';
1007           else if (i == pos + 1) *p++ = '>';
1008           else
1009             *p++ = ' ';
1010         }
1011       *p++ = ']';
1012
1013     }
1014  ++bp->tick;
1015
1016   /* " 234,567,890" */
1017   sprintf (p, " %s", size_grouped);
1018   move_to_end (p);
1019   /* Pad with spaces to 11 chars for the size_grouped field;
1020    * couldn't use the field width specifier in sprintf, because
1021    * it counts in bytes, not characters. */
1022   for (size_grouped_pad = 11 - size_grouped_len;
1023        size_grouped_pad > 0;
1024        --size_grouped_pad)
1025     {
1026       *p++ = ' ';
1027     }
1028
1029   /* " 12.52Kb/s or 12.52KB/s" */
1030   if (hist->total_time > 0 && hist->total_bytes)
1031     {
1032       static const char *short_units[] = { "B/s", "KB/s", "MB/s", "GB/s" };
1033       static const char *short_units_bits[] = { "b/s", "Kb/s", "Mb/s", "Gb/s" };
1034       int units = 0;
1035       /* Calculate the download speed using the history ring and
1036          recent data that hasn't made it to the ring yet.  */
1037       wgint dlquant = hist->total_bytes + bp->recent_bytes;
1038       double dltime = hist->total_time + (dl_total_time - bp->recent_start);
1039       double dlspeed = calc_rate (dlquant, dltime, &units);
1040       sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
1041                dlspeed,  !opt.report_bps ? short_units[units] : short_units_bits[units]);
1042       move_to_end (p);
1043     }
1044   else
1045     APPEND_LITERAL (" --.-K/s");
1046
1047   if (!done)
1048     {
1049       /* "  eta ..m ..s"; wait for three seconds before displaying the ETA.
1050          That's because the ETA value needs a while to become
1051          reliable.  */
1052       if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
1053         {
1054           int eta;
1055
1056           /* Don't change the value of ETA more than approximately once
1057              per second; doing so would cause flashing without providing
1058              any value to the user. */
1059           if (bp->total_length != size
1060               && bp->last_eta_value != 0
1061               && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
1062             eta = bp->last_eta_value;
1063           else
1064             {
1065               /* Calculate ETA using the average download speed to predict
1066                  the future speed.  If you want to use a speed averaged
1067                  over a more recent period, replace dl_total_time with
1068                  hist->total_time and bp->count with hist->total_bytes.
1069                  I found that doing that results in a very jerky and
1070                  ultimately unreliable ETA.  */
1071               wgint bytes_remaining = bp->total_length - size;
1072               double eta_ = dl_total_time * bytes_remaining / bp->count;
1073               if (eta_ >= INT_MAX - 1)
1074                 goto skip_eta;
1075               eta = (int) (eta_ + 0.5);
1076               bp->last_eta_value = eta;
1077               bp->last_eta_time = dl_total_time;
1078             }
1079
1080           sprintf (p, get_eta(&bytes_cols_diff),
1081                    eta_to_human_short (eta, false));
1082           move_to_end (p);
1083         }
1084       else if (bp->total_length > 0)
1085         {
1086         skip_eta:
1087           APPEND_LITERAL ("             ");
1088         }
1089     }
1090   else
1091     {
1092       /* When the download is done, print the elapsed time.  */
1093       int nbytes;
1094       int ncols;
1095
1096       /* Note to translators: this should not take up more room than
1097          available here.  Abbreviate if necessary.  */
1098       strcpy (p, _("   in "));
1099       nbytes = strlen (p);
1100       ncols  = count_cols (p);
1101       bytes_cols_diff = nbytes - ncols;
1102       p += nbytes;
1103       if (dl_total_time >= 10)
1104         strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
1105       else
1106         sprintf (p, "%ss", print_decimal (dl_total_time));
1107       move_to_end (p);
1108     }
1109
1110   while (p - bp->buffer - bytes_cols_diff - size_grouped_diff < bp->width)
1111     *p++ = ' ';
1112   *p = '\0';
1113 }
1114
1115 /* Print the contents of the buffer as a one-line ASCII "image" so
1116    that it can be overwritten next time.  */
1117
1118 static void
1119 display_image (char *buf)
1120 {
1121   bool old = log_set_save_context (false);
1122   logputs (LOG_PROGRESS, "\r");
1123   logputs (LOG_PROGRESS, buf);
1124   log_set_save_context (old);
1125 }
1126
1127 static void
1128 bar_set_params (const char *params)
1129 {
1130   char *term = getenv ("TERM");
1131
1132   if (params
1133       && 0 == strcmp (params, "force"))
1134     current_impl_locked = 1;
1135
1136   if ((opt.lfilename
1137 #ifdef HAVE_ISATTY
1138        /* The progress bar doesn't make sense if the output is not a
1139           TTY -- when logging to file, it is better to review the
1140           dots.  */
1141        || !isatty (fileno (stderr))
1142 #endif
1143        /* Normally we don't depend on terminal type because the
1144           progress bar only uses ^M to move the cursor to the
1145           beginning of line, which works even on dumb terminals.  But
1146           Jamie Zawinski reports that ^M and ^H tricks don't work in
1147           Emacs shell buffers, and only make a mess.  */
1148        || (term && 0 == strcmp (term, "emacs"))
1149        )
1150       && !current_impl_locked)
1151     {
1152       /* We're not printing to a TTY, so revert to the fallback
1153          display.  #### We're recursively calling
1154          set_progress_implementation here, which is slightly kludgy.
1155          It would be nicer if we provided that function a return value
1156          indicating a failure of some sort.  */
1157       set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1158       return;
1159     }
1160 }
1161
1162 #ifdef SIGWINCH
1163 void
1164 progress_handle_sigwinch (int sig)
1165 {
1166   received_sigwinch = 1;
1167   signal (SIGWINCH, progress_handle_sigwinch);
1168 }
1169 #endif
1170
1171 /* Provide a short human-readable rendition of the ETA.  This is like
1172    secs_to_human_time in main.c, except the output doesn't include
1173    fractions (which would look silly in by nature imprecise ETA) and
1174    takes less room.  If the time is measured in hours, hours and
1175    minutes (but not seconds) are shown; if measured in days, then days
1176    and hours are shown.  This ensures brevity while still displaying
1177    as much as possible.
1178
1179    If CONDENSED is true, the separator between minutes and seconds
1180    (and hours and minutes, etc.) is not included, shortening the
1181    display by one additional character.  This is used for dot
1182    progress.
1183
1184    The display never occupies more than 7 characters of screen
1185    space.  */
1186
1187 static const char *
1188 eta_to_human_short (int secs, bool condensed)
1189 {
1190   static char buf[10];          /* 8 should be enough, but just in case */
1191   static int last = -1;
1192   const char *space = condensed ? "" : " ";
1193
1194   /* Trivial optimization.  create_image can call us every 200 msecs
1195      (see bar_update) for fast downloads, but ETA will only change
1196      once per 900 msecs.  */
1197   if (secs == last)
1198     return buf;
1199   last = secs;
1200
1201   if (secs < 100)
1202     sprintf (buf, "%ds", secs);
1203   else if (secs < 100 * 60)
1204     sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1205   else if (secs < 48 * 3600)
1206     sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1207   else if (secs < 100 * 86400)
1208     sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 24);
1209   else
1210     /* even (2^31-1)/86400 doesn't overflow BUF. */
1211     sprintf (buf, "%dd", secs / 86400);
1212
1213   return buf;
1214 }