]> sjero.net Git - wget/blob - src/progress.c
[svn] Doc fix.
[wget] / src / progress.c
1 /* Download progress.
2    Copyright (C) 2001, 2002 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
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, 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 in milliseconds 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 >= 100 ? 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           double secs_sofar = dltime / 1000;
324           int eta = (int) (secs_sofar * bytes_remaining / bytes_sofar + 0.5);
325           logprintf (LOG_VERBOSE, " %s", eta_to_human_short (eta, true));
326         }
327     }
328   else
329     {
330       /* When done, print the total download time */
331       double secs = dltime / 1000;
332       if (secs >= 10)
333         logprintf (LOG_VERBOSE, "=%s",
334                    eta_to_human_short ((int) (secs + 0.5), true));
335       else
336         logprintf (LOG_VERBOSE, "=%ss", print_decimal (secs));
337     }
338 }
339
340 /* Dot-progress backend for progress_update. */
341
342 static void
343 dot_update (void *progress, wgint howmuch, double dltime)
344 {
345   struct dot_progress *dp = progress;
346   int dot_bytes = opt.dot_bytes;
347   wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
348
349   log_set_flush (false);
350
351   dp->accumulated += howmuch;
352   for (; dp->accumulated >= dot_bytes; dp->accumulated -= dot_bytes)
353     {
354       if (dp->dots == 0)
355         logprintf (LOG_VERBOSE, "\n%6sK",
356                    number_to_static_string (dp->rows * ROW_BYTES / 1024));
357
358       if (dp->dots % opt.dot_spacing == 0)
359         logputs (LOG_VERBOSE, " ");
360       logputs (LOG_VERBOSE, ".");
361
362       ++dp->dots;
363       if (dp->dots >= opt.dots_in_line)
364         {
365           wgint row_qty = ROW_BYTES;
366           if (dp->rows == dp->initial_length / ROW_BYTES)
367             row_qty -= dp->initial_length % ROW_BYTES;
368
369           ++dp->rows;
370           dp->dots = 0;
371
372           print_row_stats (dp, dltime, false);
373         }
374     }
375
376   log_set_flush (true);
377 }
378
379 /* Dot-progress backend for progress_finish. */
380
381 static void
382 dot_finish (void *progress, double dltime)
383 {
384   struct dot_progress *dp = progress;
385   wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
386   int i;
387
388   log_set_flush (false);
389
390   if (dp->dots == 0)
391     logprintf (LOG_VERBOSE, "\n%6sK",
392                number_to_static_string (dp->rows * ROW_BYTES / 1024));
393   for (i = dp->dots; i < opt.dots_in_line; i++)
394     {
395       if (i % opt.dot_spacing == 0)
396         logputs (LOG_VERBOSE, " ");
397       logputs (LOG_VERBOSE, " ");
398     }
399
400   print_row_stats (dp, dltime, true);
401   logputs (LOG_VERBOSE, "\n\n");
402   log_set_flush (false);
403
404   xfree (dp);
405 }
406
407 /* This function interprets the progress "parameters".  For example,
408    if Wget is invoked with --progress=dot:mega, it will set the
409    "dot-style" to "mega".  Valid styles are default, binary, mega, and
410    giga.  */
411
412 static void
413 dot_set_params (const char *params)
414 {
415   if (!params || !*params)
416     params = opt.dot_style;
417
418   if (!params)
419     return;
420
421   /* We use this to set the retrieval style.  */
422   if (!strcasecmp (params, "default"))
423     {
424       /* Default style: 1K dots, 10 dots in a cluster, 50 dots in a
425          line.  */
426       opt.dot_bytes = 1024;
427       opt.dot_spacing = 10;
428       opt.dots_in_line = 50;
429     }
430   else if (!strcasecmp (params, "binary"))
431     {
432       /* "Binary" retrieval: 8K dots, 16 dots in a cluster, 48 dots
433          (384K) in a line.  */
434       opt.dot_bytes = 8192;
435       opt.dot_spacing = 16;
436       opt.dots_in_line = 48;
437     }
438   else if (!strcasecmp (params, "mega"))
439     {
440       /* "Mega" retrieval, for retrieving very long files; each dot is
441          64K, 8 dots in a cluster, 6 clusters (3M) in a line.  */
442       opt.dot_bytes = 65536L;
443       opt.dot_spacing = 8;
444       opt.dots_in_line = 48;
445     }
446   else if (!strcasecmp (params, "giga"))
447     {
448       /* "Giga" retrieval, for retrieving very very *very* long files;
449          each dot is 1M, 8 dots in a cluster, 4 clusters (32M) in a
450          line.  */
451       opt.dot_bytes = (1L << 20);
452       opt.dot_spacing = 8;
453       opt.dots_in_line = 32;
454     }
455   else
456     fprintf (stderr,
457              _("Invalid dot style specification `%s'; leaving unchanged.\n"),
458              params);
459 }
460 \f
461 /* "Thermometer" (bar) progress. */
462
463 /* Assumed screen width if we can't find the real value.  */
464 #define DEFAULT_SCREEN_WIDTH 80
465
466 /* Minimum screen width we'll try to work with.  If this is too small,
467    create_image will overflow the buffer.  */
468 #define MINIMUM_SCREEN_WIDTH 45
469
470 /* The last known screen width.  This can be updated by the code that
471    detects that SIGWINCH was received (but it's never updated from the
472    signal handler).  */
473 static int screen_width;
474
475 /* A flag that, when set, means SIGWINCH was received.  */
476 static volatile sig_atomic_t received_sigwinch;
477
478 /* Size of the download speed history ring. */
479 #define DLSPEED_HISTORY_SIZE 20
480
481 /* The minimum time length of a history sample.  By default, each
482    sample is at least 150ms long, which means that, over the course of
483    20 samples, "current" download speed spans at least 3s into the
484    past.  */
485 #define DLSPEED_SAMPLE_MIN 150
486
487 /* The time after which the download starts to be considered
488    "stalled", i.e. the current bandwidth is not printed and the recent
489    download speeds are scratched.  */
490 #define STALL_START_TIME 5000
491
492 struct bar_progress {
493   wgint initial_length;         /* how many bytes have been downloaded
494                                    previously. */
495   wgint total_length;           /* expected total byte count when the
496                                    download finishes */
497   wgint count;                  /* bytes downloaded so far */
498
499   double last_screen_update;    /* time of the last screen update,
500                                    measured since the beginning of
501                                    download. */
502
503   int width;                    /* screen width we're using at the
504                                    time the progress gauge was
505                                    created.  this is different from
506                                    the screen_width global variable in
507                                    that the latter can be changed by a
508                                    signal. */
509   char *buffer;                 /* buffer where the bar "image" is
510                                    stored. */
511   int tick;                     /* counter used for drawing the
512                                    progress bar where the total size
513                                    is not known. */
514
515   /* The following variables (kept in a struct for namespace reasons)
516      keep track of recent download speeds.  See bar_update() for
517      details.  */
518   struct bar_progress_hist {
519     int pos;
520     wgint times[DLSPEED_HISTORY_SIZE];
521     wgint bytes[DLSPEED_HISTORY_SIZE];
522
523     /* The sum of times and bytes respectively, maintained for
524        efficiency. */
525     wgint total_time;
526     wgint total_bytes;
527   } hist;
528
529   double recent_start;          /* timestamp of beginning of current
530                                    position. */
531   wgint recent_bytes;           /* bytes downloaded so far. */
532
533   bool stalled;                 /* set when no data arrives for longer
534                                    than STALL_START_TIME, then reset
535                                    when new data arrives. */
536
537   /* create_image() uses these to make sure that ETA information
538      doesn't flicker. */
539   double last_eta_time;         /* time of the last update to download
540                                    speed and ETA, measured since the
541                                    beginning of download. */
542   int last_eta_value;
543 };
544
545 static void create_image (struct bar_progress *, double, bool);
546 static void display_image (char *);
547
548 static void *
549 bar_create (wgint initial, wgint total)
550 {
551   struct bar_progress *bp = xnew0 (struct bar_progress);
552
553   /* In theory, our callers should take care of this pathological
554      case, but it can sometimes happen. */
555   if (initial > total)
556     total = initial;
557
558   bp->initial_length = initial;
559   bp->total_length   = total;
560
561   /* Initialize screen_width if this hasn't been done or if it might
562      have changed, as indicated by receiving SIGWINCH.  */
563   if (!screen_width || received_sigwinch)
564     {
565       screen_width = determine_screen_width ();
566       if (!screen_width)
567         screen_width = DEFAULT_SCREEN_WIDTH;
568       else if (screen_width < MINIMUM_SCREEN_WIDTH)
569         screen_width = MINIMUM_SCREEN_WIDTH;
570       received_sigwinch = 0;
571     }
572
573   /* - 1 because we don't want to use the last screen column. */
574   bp->width = screen_width - 1;
575   /* + 1 for the terminating zero. */
576   bp->buffer = xmalloc (bp->width + 1);
577
578   logputs (LOG_VERBOSE, "\n");
579
580   create_image (bp, 0, false);
581   display_image (bp->buffer);
582
583   return bp;
584 }
585
586 static void update_speed_ring (struct bar_progress *, wgint, double);
587
588 static void
589 bar_update (void *progress, wgint howmuch, double dltime)
590 {
591   struct bar_progress *bp = progress;
592   bool force_screen_update = false;
593
594   bp->count += howmuch;
595   if (bp->total_length > 0
596       && bp->count + bp->initial_length > bp->total_length)
597     /* We could be downloading more than total_length, e.g. when the
598        server sends an incorrect Content-Length header.  In that case,
599        adjust bp->total_length to the new reality, so that the code in
600        create_image() that depends on total size being smaller or
601        equal to the expected size doesn't abort.  */
602     bp->total_length = bp->initial_length + bp->count;
603
604   update_speed_ring (bp, howmuch, dltime);
605
606   /* If SIGWINCH (the window size change signal) been received,
607      determine the new screen size and update the screen.  */
608   if (received_sigwinch)
609     {
610       int old_width = screen_width;
611       screen_width = determine_screen_width ();
612       if (!screen_width)
613         screen_width = DEFAULT_SCREEN_WIDTH;
614       else if (screen_width < MINIMUM_SCREEN_WIDTH)
615         screen_width = MINIMUM_SCREEN_WIDTH;
616       if (screen_width != old_width)
617         {
618           bp->width = screen_width - 1;
619           bp->buffer = xrealloc (bp->buffer, bp->width + 1);
620           force_screen_update = true;
621         }
622       received_sigwinch = 0;
623     }
624
625   if (dltime - bp->last_screen_update < 200 && !force_screen_update)
626     /* Don't update more often than five times per second. */
627     return;
628
629   create_image (bp, dltime, false);
630   display_image (bp->buffer);
631   bp->last_screen_update = dltime;
632 }
633
634 static void
635 bar_finish (void *progress, double dltime)
636 {
637   struct bar_progress *bp = progress;
638
639   if (bp->total_length > 0
640       && bp->count + bp->initial_length > bp->total_length)
641     /* See bar_update() for explanation. */
642     bp->total_length = bp->initial_length + bp->count;
643
644   create_image (bp, dltime, true);
645   display_image (bp->buffer);
646
647   logputs (LOG_VERBOSE, "\n\n");
648
649   xfree (bp->buffer);
650   xfree (bp);
651 }
652
653 /* This code attempts to maintain the notion of a "current" download
654    speed, over the course of no less than 3s.  (Shorter intervals
655    produce very erratic results.)
656
657    To do so, it samples the speed in 150ms intervals and stores the
658    recorded samples in a FIFO history ring.  The ring stores no more
659    than 20 intervals, hence the history covers the period of at least
660    three seconds and at most 20 reads into the past.  This method
661    should produce reasonable results for downloads ranging from very
662    slow to very fast.
663
664    The idea is that for fast downloads, we get the speed over exactly
665    the last three seconds.  For slow downloads (where a network read
666    takes more than 150ms to complete), we get the speed over a larger
667    time period, as large as it takes to complete thirty reads.  This
668    is good because slow downloads tend to fluctuate more and a
669    3-second average would be too erratic.  */
670
671 static void
672 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
673 {
674   struct bar_progress_hist *hist = &bp->hist;
675   double recent_age = dltime - bp->recent_start;
676
677   /* Update the download count. */
678   bp->recent_bytes += howmuch;
679
680   /* For very small time intervals, we return after having updated the
681      "recent" download count.  When its age reaches or exceeds minimum
682      sample time, it will be recorded in the history ring.  */
683   if (recent_age < DLSPEED_SAMPLE_MIN)
684     return;
685
686   if (howmuch == 0)
687     {
688       /* If we're not downloading anything, we might be stalling,
689          i.e. not downloading anything for an extended period of time.
690          Since 0-reads do not enter the history ring, recent_age
691          effectively measures the time since last read.  */
692       if (recent_age >= STALL_START_TIME)
693         {
694           /* If we're stalling, reset the ring contents because it's
695              stale and because it will make bar_update stop printing
696              the (bogus) current bandwidth.  */
697           bp->stalled = true;
698           xzero (*hist);
699           bp->recent_bytes = 0;
700         }
701       return;
702     }
703
704   /* We now have a non-zero amount of to store to the speed ring.  */
705
706   /* If the stall status was acquired, reset it. */
707   if (bp->stalled)
708     {
709       bp->stalled = false;
710       /* "recent_age" includes the the entired stalled period, which
711          could be very long.  Don't update the speed ring with that
712          value because the current bandwidth would start too small.
713          Start with an arbitrary (but more reasonable) time value and
714          let it level out.  */
715       recent_age = 1000;
716     }
717
718   /* Store "recent" bytes and download time to history ring at the
719      position POS.  */
720
721   /* To correctly maintain the totals, first invalidate existing data
722      (least recent in time) at this position. */
723   hist->total_time  -= hist->times[hist->pos];
724   hist->total_bytes -= hist->bytes[hist->pos];
725
726   /* Now store the new data and update the totals. */
727   hist->times[hist->pos] = recent_age;
728   hist->bytes[hist->pos] = bp->recent_bytes;
729   hist->total_time  += recent_age;
730   hist->total_bytes += bp->recent_bytes;
731
732   /* Start a new "recent" period. */
733   bp->recent_start = dltime;
734   bp->recent_bytes = 0;
735
736   /* Advance the current ring position. */
737   if (++hist->pos == DLSPEED_HISTORY_SIZE)
738     hist->pos = 0;
739
740 #if 0
741   /* Sledgehammer check to verify that the totals are accurate. */
742   {
743     int i;
744     double sumt = 0, sumb = 0;
745     for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
746       {
747         sumt += hist->times[i];
748         sumb += hist->bytes[i];
749       }
750     assert (sumt == hist->total_time);
751     assert (sumb == hist->total_bytes);
752   }
753 #endif
754 }
755
756 #define APPEND_LITERAL(s) do {                  \
757   memcpy (p, s, sizeof (s) - 1);                \
758   p += sizeof (s) - 1;                          \
759 } while (0)
760
761 /* Use move_to_end (s) to get S to point the end of the string (the
762    terminating \0).  This is faster than s+=strlen(s), but some people
763    are confused when they see strchr (s, '\0') in the code.  */
764 #define move_to_end(s) s = strchr (s, '\0');
765
766 #ifndef MAX
767 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
768 #endif
769
770 static void
771 create_image (struct bar_progress *bp, double dl_total_time, bool done)
772 {
773   char *p = bp->buffer;
774   wgint size = bp->initial_length + bp->count;
775
776   const char *size_grouped = with_thousand_seps (size);
777   int size_grouped_len = strlen (size_grouped);
778
779   struct bar_progress_hist *hist = &bp->hist;
780
781   /* The progress bar should look like this:
782      xx% [=======>             ] nn,nnn 12.34K/s  eta 36m 51s
783
784      Calculate the geometry.  The idea is to assign as much room as
785      possible to the progress bar.  The other idea is to never let
786      things "jitter", i.e. pad elements that vary in size so that
787      their variance does not affect the placement of other elements.
788      It would be especially bad for the progress bar to be resized
789      randomly.
790
791      "xx% " or "100%"  - percentage               - 4 chars
792      "[]"              - progress bar decorations - 2 chars
793      " nnn,nnn,nnn"    - downloaded bytes         - 12 chars or very rarely more
794      " 1012.56K/s"     - dl rate                  - 11 chars
795      "  eta 36m 51s"   - ETA                      - 13 chars
796
797      "=====>..."       - progress bar             - the rest
798   */
799   int dlbytes_size = 1 + MAX (size_grouped_len, 11);
800   int progress_size = bp->width - (4 + 2 + dlbytes_size + 11 + 13);
801
802   if (progress_size < 5)
803     progress_size = 0;
804
805   /* "xx% " */
806   if (bp->total_length > 0)
807     {
808       int percentage = 100.0 * size / bp->total_length;
809       assert (percentage <= 100);
810
811       if (percentage < 100)
812         sprintf (p, "%2d%% ", percentage);
813       else
814         strcpy (p, "100%");
815       p += 4;
816     }
817   else
818     APPEND_LITERAL ("    ");
819
820   /* The progress bar: "[====>      ]" or "[++==>      ]". */
821   if (progress_size && bp->total_length > 0)
822     {
823       /* Size of the initial portion. */
824       int insz = (double)bp->initial_length / bp->total_length * progress_size;
825
826       /* Size of the downloaded portion. */
827       int dlsz = (double)size / bp->total_length * progress_size;
828
829       char *begin;
830       int i;
831
832       assert (dlsz <= progress_size);
833       assert (insz <= dlsz);
834
835       *p++ = '[';
836       begin = p;
837
838       /* Print the initial portion of the download with '+' chars, the
839          rest with '=' and one '>'.  */
840       for (i = 0; i < insz; i++)
841         *p++ = '+';
842       dlsz -= insz;
843       if (dlsz > 0)
844         {
845           for (i = 0; i < dlsz - 1; i++)
846             *p++ = '=';
847           *p++ = '>';
848         }
849
850       while (p - begin < progress_size)
851         *p++ = ' ';
852       *p++ = ']';
853     }
854   else if (progress_size)
855     {
856       /* If we can't draw a real progress bar, then at least show
857          *something* to the user.  */
858       int ind = bp->tick % (progress_size * 2 - 6);
859       int i, pos;
860
861       /* Make the star move in two directions. */
862       if (ind < progress_size - 2)
863         pos = ind + 1;
864       else
865         pos = progress_size - (ind - progress_size + 5);
866
867       *p++ = '[';
868       for (i = 0; i < progress_size; i++)
869         {
870           if      (i == pos - 1) *p++ = '<';
871           else if (i == pos    ) *p++ = '=';
872           else if (i == pos + 1) *p++ = '>';
873           else
874             *p++ = ' ';
875         }
876       *p++ = ']';
877
878       ++bp->tick;
879     }
880
881   /* " 234,567,890" */
882   sprintf (p, " %-11s", size_grouped);
883   move_to_end (p);
884
885   /* " 1012.45K/s" */
886   if (hist->total_time && hist->total_bytes)
887     {
888       static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" };
889       int units = 0;
890       /* Calculate the download speed using the history ring and
891          recent data that hasn't made it to the ring yet.  */
892       wgint dlquant = hist->total_bytes + bp->recent_bytes;
893       double dltime = hist->total_time + (dl_total_time - bp->recent_start);
894       double dlspeed = calc_rate (dlquant, dltime, &units);
895       sprintf (p, " %7.2f%s", dlspeed, short_units[units]);
896       move_to_end (p);
897     }
898   else
899     APPEND_LITERAL ("   --.--K/s");
900
901   if (!done)
902     {
903       /* "  eta ..m ..s"; wait for three seconds before displaying the ETA.
904          That's because the ETA value needs a while to become
905          reliable.  */
906       if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3000)
907         {
908           int eta;
909
910           /* Don't change the value of ETA more than approximately once
911              per second; doing so would cause flashing without providing
912              any value to the user. */
913           if (bp->total_length != size
914               && bp->last_eta_value != 0
915               && dl_total_time - bp->last_eta_time < 900)
916             eta = bp->last_eta_value;
917           else
918             {
919               /* Calculate ETA using the average download speed to predict
920                  the future speed.  If you want to use a speed averaged
921                  over a more recent period, replace dl_total_time with
922                  hist->total_time and bp->count with hist->total_bytes.
923                  I found that doing that results in a very jerky and
924                  ultimately unreliable ETA.  */
925               double time_sofar = (double) dl_total_time / 1000;
926               wgint bytes_remaining = bp->total_length - size;
927               eta = (int) (time_sofar * bytes_remaining / bp->count + 0.5);
928               bp->last_eta_value = eta;
929               bp->last_eta_time = dl_total_time;
930             }
931
932           /* Translation note: "ETA" is English-centric, but this must
933              be short, ideally 3 chars.  Abbreviate if necessary.  */
934           sprintf (p, _("  eta %s"), eta_to_human_short (eta, false));
935           move_to_end (p);
936         }
937       else if (bp->total_length > 0)
938         {
939           APPEND_LITERAL ("             ");
940         }
941     }
942   else
943     {
944       /* When the download is done, print the elapsed time.  */
945       double secs = dl_total_time / 1000;
946       /* Note to translators: this should not take up more room than
947          available here.  Abbreviate if necessary.  */
948       strcpy (p, _("   in "));
949       move_to_end (p);          /* not p+=6, think translations! */
950       if (secs >= 10)
951         strcpy (p, eta_to_human_short ((int) (secs + 0.5), false));
952       else
953         sprintf (p, "%ss", print_decimal (secs));
954       move_to_end (p);
955     }
956
957   assert (p - bp->buffer <= bp->width);
958
959   while (p < bp->buffer + bp->width)
960     *p++ = ' ';
961   *p = '\0';
962 }
963
964 /* Print the contents of the buffer as a one-line ASCII "image" so
965    that it can be overwritten next time.  */
966
967 static void
968 display_image (char *buf)
969 {
970   bool old = log_set_save_context (false);
971   logputs (LOG_VERBOSE, "\r");
972   logputs (LOG_VERBOSE, buf);
973   log_set_save_context (old);
974 }
975
976 static void
977 bar_set_params (const char *params)
978 {
979   char *term = getenv ("TERM");
980
981   if (params
982       && 0 == strcmp (params, "force"))
983     current_impl_locked = 1;
984
985   if ((opt.lfilename
986 #ifdef HAVE_ISATTY
987        /* The progress bar doesn't make sense if the output is not a
988           TTY -- when logging to file, it is better to review the
989           dots.  */
990        || !isatty (fileno (stderr))
991 #endif
992        /* Normally we don't depend on terminal type because the
993           progress bar only uses ^M to move the cursor to the
994           beginning of line, which works even on dumb terminals.  But
995           Jamie Zawinski reports that ^M and ^H tricks don't work in
996           Emacs shell buffers, and only make a mess.  */
997        || (term && 0 == strcmp (term, "emacs"))
998        )
999       && !current_impl_locked)
1000     {
1001       /* We're not printing to a TTY, so revert to the fallback
1002          display.  #### We're recursively calling
1003          set_progress_implementation here, which is slightly kludgy.
1004          It would be nicer if we provided that function a return value
1005          indicating a failure of some sort.  */
1006       set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1007       return;
1008     }
1009 }
1010
1011 #ifdef SIGWINCH
1012 void
1013 progress_handle_sigwinch (int sig)
1014 {
1015   received_sigwinch = 1;
1016   signal (SIGWINCH, progress_handle_sigwinch);
1017 }
1018 #endif
1019
1020 /* Provide a short human-readable rendition of the ETA.  This is like
1021    secs_to_human_time in main.c, except the output doesn't include
1022    fractions (which would look silly in by nature imprecise ETA) and
1023    takes less room.  If the time is measured in hours, hours and
1024    minutes (but not seconds) are shown; if measured in days, then days
1025    and hours are shown.  This ensures brevity while still displaying
1026    as much as possible.
1027
1028    If CONDENSED is true, the separator between minutes and seconds
1029    (and hours and minutes, etc.) is not included, shortening the
1030    display by one additional character.  This is used for dot
1031    progress.
1032
1033    The display never occupies more than 7 characters of screen
1034    space.  */
1035
1036 static const char *
1037 eta_to_human_short (int secs, bool condensed)
1038 {
1039   static char buf[10];          /* 8 should be enough, but just in case */
1040   static int last = -1;
1041   const char *space = condensed ? "" : " ";
1042
1043   /* Trivial optimization.  create_image can call us every 200 msecs
1044      (see bar_update) for fast downloads, but ETA will only change
1045      once per 900 msecs.  */
1046   if (secs == last)
1047     return buf;
1048   last = secs;
1049
1050   if (secs < 100)
1051     sprintf (buf, "%ds", secs);
1052   else if (secs < 100 * 60)
1053     sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1054   else if (secs < 100 * 3600)
1055     sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1056   else if (secs < 100 * 86400)
1057     sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 60);
1058   else
1059     /* even (2^31-1)/86400 doesn't overflow BUF. */
1060     sprintf (buf, "%dd", secs / 86400);
1061
1062   return buf;
1063 }