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