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