2 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009
3 Free Software Foundation, Inc.
5 This file is part of GNU Wget.
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.
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.
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/>.
20 Additional permission under GNU GPL version 3 section 7
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. */
49 struct progress_implementation {
52 void *(*create) (wgint, wgint);
53 void (*update) (void *, wgint, double);
54 void (*finish) (void *, double);
55 void (*set_params) (const char *);
58 /* Necessary forward declarations. */
60 static void *dot_create (wgint, wgint);
61 static void dot_update (void *, wgint, double);
62 static void dot_finish (void *, double);
63 static void dot_set_params (const char *);
65 static void *bar_create (wgint, wgint);
66 static void bar_update (void *, wgint, double);
67 static void bar_finish (void *, double);
68 static void bar_set_params (const char *);
70 static struct progress_implementation implementations[] = {
71 { "dot", 0, dot_create, dot_update, dot_finish, dot_set_params },
72 { "bar", 1, bar_create, bar_update, bar_finish, bar_set_params }
74 static struct progress_implementation *current_impl;
75 static int current_impl_locked;
77 /* Progress implementation used by default. Can be overriden in
78 wgetrc or by the fallback one. */
80 #define DEFAULT_PROGRESS_IMPLEMENTATION "bar"
82 /* Fallback progress implementation should be something that works
83 under all display types. If you put something other than "dot"
84 here, remember that bar_set_params tries to switch to this if we're
85 not running on a TTY. So changing this to "bar" could cause
88 #define FALLBACK_PROGRESS_IMPLEMENTATION "dot"
90 /* Return true if NAME names a valid progress bar implementation. The
91 characters after the first : will be ignored. */
94 valid_progress_implementation_p (const char *name)
97 struct progress_implementation *pi = implementations;
98 char *colon = strchr (name, ':');
99 size_t namelen = colon ? (size_t) (colon - name) : strlen (name);
101 for (i = 0; i < countof (implementations); i++, pi++)
102 if (!strncmp (pi->name, name, namelen))
107 /* Set the progress implementation to NAME. */
110 set_progress_implementation (const char *name)
113 struct progress_implementation *pi = implementations;
117 name = DEFAULT_PROGRESS_IMPLEMENTATION;
119 colon = strchr (name, ':');
120 namelen = colon ? (size_t) (colon - name) : strlen (name);
122 for (i = 0; i < countof (implementations); i++, pi++)
123 if (!strncmp (pi->name, name, namelen))
126 current_impl_locked = 0;
129 /* We call pi->set_params even if colon is NULL because we
130 want to give the implementation a chance to set up some
131 things it needs to run. */
135 pi->set_params (colon);
141 static int output_redirected;
144 progress_schedule_redirect (void)
146 output_redirected = 1;
149 /* Create a progress gauge. INITIAL is the number of bytes the
150 download starts from (zero if the download starts from scratch).
151 TOTAL is the expected total number of bytes in this download. If
152 TOTAL is zero, it means that the download size is not known in
156 progress_create (wgint initial, wgint total)
158 /* Check if the log status has changed under our feet. */
159 if (output_redirected)
161 if (!current_impl_locked)
162 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
163 output_redirected = 0;
166 return current_impl->create (initial, total);
169 /* Return true if the progress gauge is "interactive", i.e. if it can
170 profit from being called regularly even in absence of data. The
171 progress bar is interactive because it regularly updates the ETA
172 and current update. */
175 progress_interactive_p (void *progress)
177 return current_impl->interactive;
180 /* Inform the progress gauge of newly received bytes. DLTIME is the
181 time since the beginning of the download. */
184 progress_update (void *progress, wgint howmuch, double dltime)
186 current_impl->update (progress, howmuch, dltime);
189 /* Tell the progress gauge to clean up. Calling this will free the
190 PROGRESS object, the further use of which is not allowed. */
193 progress_finish (void *progress, double dltime)
195 current_impl->finish (progress, dltime);
200 struct dot_progress {
201 wgint initial_length; /* how many bytes have been downloaded
203 wgint total_length; /* expected total byte count when the
206 int accumulated; /* number of bytes accumulated after
207 the last printed dot */
209 int rows; /* number of rows printed so far */
210 int dots; /* number of dots printed in this row */
212 double last_timer_value;
215 /* Dot-progress backend for progress_create. */
218 dot_create (wgint initial, wgint total)
220 struct dot_progress *dp = xnew0 (struct dot_progress);
221 dp->initial_length = initial;
222 dp->total_length = total;
224 if (dp->initial_length)
226 int dot_bytes = opt.dot_bytes;
227 const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
229 int remainder = dp->initial_length % ROW_BYTES;
230 wgint skipped = dp->initial_length - remainder;
234 wgint skipped_k = skipped / 1024; /* skipped amount in K */
235 int skipped_k_len = numdigit (skipped_k);
236 if (skipped_k_len < 6)
239 /* Align the [ skipping ... ] line with the dots. To do
240 that, insert the number of spaces equal to the number of
241 digits in the skipped amount in K. */
242 logprintf (LOG_VERBOSE, _("\n%*s[ skipping %sK ]"),
243 2 + skipped_k_len, "",
244 number_to_static_string (skipped_k));
247 logprintf (LOG_VERBOSE, "\n%6sK",
248 number_to_static_string (skipped / 1024));
249 for (; remainder >= dot_bytes; remainder -= dot_bytes)
251 if (dp->dots % opt.dot_spacing == 0)
252 logputs (LOG_VERBOSE, " ");
253 logputs (LOG_VERBOSE, ",");
256 assert (dp->dots < opt.dots_in_line);
258 dp->accumulated = remainder;
259 dp->rows = skipped / ROW_BYTES;
265 static const char *eta_to_human_short (int, bool);
267 /* Prints the stats (percentage of completion, speed, ETA) for current
268 row. DLTIME is the time spent downloading the data in current
271 #### This function is somewhat uglified by the fact that current
272 row and last row have somewhat different stats requirements. It
273 might be worthwhile to split it to two different functions. */
276 print_row_stats (struct dot_progress *dp, double dltime, bool last)
278 const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
280 /* bytes_displayed is the number of bytes indicated to the user by
281 dots printed so far, includes the initially "skipped" amount */
282 wgint bytes_displayed = dp->rows * ROW_BYTES + dp->dots * opt.dot_bytes;
285 /* For last row also count bytes accumulated after last dot */
286 bytes_displayed += dp->accumulated;
288 if (dp->total_length)
290 /* Round to floor value to provide gauge how much data *has*
291 been retrieved. 12.8% will round to 12% because the 13% mark
292 has not yet been reached. 100% is only shown when done. */
293 int percentage = 100.0 * bytes_displayed / dp->total_length;
294 logprintf (LOG_VERBOSE, "%3d%%", percentage);
298 static char names[] = {' ', 'K', 'M', 'G'};
301 wgint bytes_this_row;
303 bytes_this_row = ROW_BYTES;
305 /* For last row also include bytes accumulated after last dot. */
306 bytes_this_row = dp->dots * opt.dot_bytes + dp->accumulated;
307 /* Don't count the portion of the row belonging to initial_length */
308 if (dp->rows == dp->initial_length / ROW_BYTES)
309 bytes_this_row -= dp->initial_length % ROW_BYTES;
310 rate = calc_rate (bytes_this_row, dltime - dp->last_timer_value, &units);
311 logprintf (LOG_VERBOSE, " %4.*f%c",
312 rate >= 99.95 ? 0 : rate >= 9.995 ? 1 : 2,
314 dp->last_timer_value = dltime;
319 /* Display ETA based on average speed. Inspired by Vladi
320 Belperchinov-Shabanski's "wget-new-percentage" patch. */
321 if (dp->total_length)
323 wgint bytes_remaining = dp->total_length - bytes_displayed;
324 /* The quantity downloaded in this download run. */
325 wgint bytes_sofar = bytes_displayed - dp->initial_length;
326 double eta = dltime * bytes_remaining / bytes_sofar;
327 if (eta < INT_MAX - 1)
328 logprintf (LOG_VERBOSE, " %s",
329 eta_to_human_short ((int) (eta + 0.5), true));
334 /* When done, print the total download time */
336 logprintf (LOG_VERBOSE, "=%s",
337 eta_to_human_short ((int) (dltime + 0.5), true));
339 logprintf (LOG_VERBOSE, "=%ss", print_decimal (dltime));
343 /* Dot-progress backend for progress_update. */
346 dot_update (void *progress, wgint howmuch, double dltime)
348 struct dot_progress *dp = progress;
349 int dot_bytes = opt.dot_bytes;
350 wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
352 log_set_flush (false);
354 dp->accumulated += howmuch;
355 for (; dp->accumulated >= dot_bytes; dp->accumulated -= dot_bytes)
358 logprintf (LOG_VERBOSE, "\n%6sK",
359 number_to_static_string (dp->rows * ROW_BYTES / 1024));
361 if (dp->dots % opt.dot_spacing == 0)
362 logputs (LOG_VERBOSE, " ");
363 logputs (LOG_VERBOSE, ".");
366 if (dp->dots >= opt.dots_in_line)
371 print_row_stats (dp, dltime, false);
375 log_set_flush (true);
378 /* Dot-progress backend for progress_finish. */
381 dot_finish (void *progress, double dltime)
383 struct dot_progress *dp = progress;
384 wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
387 log_set_flush (false);
390 logprintf (LOG_VERBOSE, "\n%6sK",
391 number_to_static_string (dp->rows * ROW_BYTES / 1024));
392 for (i = dp->dots; i < opt.dots_in_line; i++)
394 if (i % opt.dot_spacing == 0)
395 logputs (LOG_VERBOSE, " ");
396 logputs (LOG_VERBOSE, " ");
399 print_row_stats (dp, dltime, true);
400 logputs (LOG_VERBOSE, "\n\n");
401 log_set_flush (false);
406 /* This function interprets the progress "parameters". For example,
407 if Wget is invoked with --progress=dot:mega, it will set the
408 "dot-style" to "mega". Valid styles are default, binary, mega, and
412 dot_set_params (const char *params)
414 if (!params || !*params)
415 params = opt.dot_style;
420 /* We use this to set the retrieval style. */
421 if (!strcasecmp (params, "default"))
423 /* Default style: 1K dots, 10 dots in a cluster, 50 dots in a
425 opt.dot_bytes = 1024;
426 opt.dot_spacing = 10;
427 opt.dots_in_line = 50;
429 else if (!strcasecmp (params, "binary"))
431 /* "Binary" retrieval: 8K dots, 16 dots in a cluster, 48 dots
433 opt.dot_bytes = 8192;
434 opt.dot_spacing = 16;
435 opt.dots_in_line = 48;
437 else if (!strcasecmp (params, "mega"))
439 /* "Mega" retrieval, for retrieving very long files; each dot is
440 64K, 8 dots in a cluster, 6 clusters (3M) in a line. */
441 opt.dot_bytes = 65536L;
443 opt.dots_in_line = 48;
445 else if (!strcasecmp (params, "giga"))
447 /* "Giga" retrieval, for retrieving very very *very* long files;
448 each dot is 1M, 8 dots in a cluster, 4 clusters (32M) in a
450 opt.dot_bytes = (1L << 20);
452 opt.dots_in_line = 32;
456 _("Invalid dot style specification %s; leaving unchanged.\n"),
460 /* "Thermometer" (bar) progress. */
462 /* Assumed screen width if we can't find the real value. */
463 #define DEFAULT_SCREEN_WIDTH 80
465 /* Minimum screen width we'll try to work with. If this is too small,
466 create_image will overflow the buffer. */
467 #define MINIMUM_SCREEN_WIDTH 45
469 /* The last known screen width. This can be updated by the code that
470 detects that SIGWINCH was received (but it's never updated from the
472 static int screen_width;
474 /* A flag that, when set, means SIGWINCH was received. */
475 static volatile sig_atomic_t received_sigwinch;
477 /* Size of the download speed history ring. */
478 #define DLSPEED_HISTORY_SIZE 20
480 /* The minimum time length of a history sample. By default, each
481 sample is at least 150ms long, which means that, over the course of
482 20 samples, "current" download speed spans at least 3s into the
484 #define DLSPEED_SAMPLE_MIN 0.15
486 /* The time after which the download starts to be considered
487 "stalled", i.e. the current bandwidth is not printed and the recent
488 download speeds are scratched. */
489 #define STALL_START_TIME 5
491 /* Time between screen refreshes will not be shorter than this, so
492 that Wget doesn't swamp the TTY with output. */
493 #define REFRESH_INTERVAL 0.2
495 /* Don't refresh the ETA too often to avoid jerkiness in predictions.
496 This allows ETA to change approximately once per second. */
497 #define ETA_REFRESH_INTERVAL 0.99
499 struct bar_progress {
500 wgint initial_length; /* how many bytes have been downloaded
502 wgint total_length; /* expected total byte count when the
504 wgint count; /* bytes downloaded so far */
506 double last_screen_update; /* time of the last screen update,
507 measured since the beginning of
510 int width; /* screen width we're using at the
511 time the progress gauge was
512 created. this is different from
513 the screen_width global variable in
514 that the latter can be changed by a
516 char *buffer; /* buffer where the bar "image" is
518 int tick; /* counter used for drawing the
519 progress bar where the total size
522 /* The following variables (kept in a struct for namespace reasons)
523 keep track of recent download speeds. See bar_update() for
525 struct bar_progress_hist {
527 double times[DLSPEED_HISTORY_SIZE];
528 wgint bytes[DLSPEED_HISTORY_SIZE];
530 /* The sum of times and bytes respectively, maintained for
536 double recent_start; /* timestamp of beginning of current
538 wgint recent_bytes; /* bytes downloaded so far. */
540 bool stalled; /* set when no data arrives for longer
541 than STALL_START_TIME, then reset
542 when new data arrives. */
544 /* create_image() uses these to make sure that ETA information
546 double last_eta_time; /* time of the last update to download
547 speed and ETA, measured since the
548 beginning of download. */
552 static void create_image (struct bar_progress *, double, bool);
553 static void display_image (char *);
556 bar_create (wgint initial, wgint total)
558 struct bar_progress *bp = xnew0 (struct bar_progress);
560 /* In theory, our callers should take care of this pathological
561 case, but it can sometimes happen. */
565 bp->initial_length = initial;
566 bp->total_length = total;
568 /* Initialize screen_width if this hasn't been done or if it might
569 have changed, as indicated by receiving SIGWINCH. */
570 if (!screen_width || received_sigwinch)
572 screen_width = determine_screen_width ();
574 screen_width = DEFAULT_SCREEN_WIDTH;
575 else if (screen_width < MINIMUM_SCREEN_WIDTH)
576 screen_width = MINIMUM_SCREEN_WIDTH;
577 received_sigwinch = 0;
580 /* - 1 because we don't want to use the last screen column. */
581 bp->width = screen_width - 1;
582 /* + enough space for the terminating zero, and hopefully enough room
583 * for multibyte characters. */
584 bp->buffer = xmalloc (bp->width + 100);
586 logputs (LOG_VERBOSE, "\n");
588 create_image (bp, 0, false);
589 display_image (bp->buffer);
594 static void update_speed_ring (struct bar_progress *, wgint, double);
597 bar_update (void *progress, wgint howmuch, double dltime)
599 struct bar_progress *bp = progress;
600 bool force_screen_update = false;
602 bp->count += howmuch;
603 if (bp->total_length > 0
604 && bp->count + bp->initial_length > bp->total_length)
605 /* We could be downloading more than total_length, e.g. when the
606 server sends an incorrect Content-Length header. In that case,
607 adjust bp->total_length to the new reality, so that the code in
608 create_image() that depends on total size being smaller or
609 equal to the expected size doesn't abort. */
610 bp->total_length = bp->initial_length + bp->count;
612 update_speed_ring (bp, howmuch, dltime);
614 /* If SIGWINCH (the window size change signal) been received,
615 determine the new screen size and update the screen. */
616 if (received_sigwinch)
618 int old_width = screen_width;
619 screen_width = determine_screen_width ();
621 screen_width = DEFAULT_SCREEN_WIDTH;
622 else if (screen_width < MINIMUM_SCREEN_WIDTH)
623 screen_width = MINIMUM_SCREEN_WIDTH;
624 if (screen_width != old_width)
626 bp->width = screen_width - 1;
627 bp->buffer = xrealloc (bp->buffer, bp->width + 100);
628 force_screen_update = true;
630 received_sigwinch = 0;
633 if (dltime - bp->last_screen_update < REFRESH_INTERVAL && !force_screen_update)
634 /* Don't update more often than five times per second. */
637 create_image (bp, dltime, false);
638 display_image (bp->buffer);
639 bp->last_screen_update = dltime;
643 bar_finish (void *progress, double dltime)
645 struct bar_progress *bp = progress;
647 if (bp->total_length > 0
648 && bp->count + bp->initial_length > bp->total_length)
649 /* See bar_update() for explanation. */
650 bp->total_length = bp->initial_length + bp->count;
652 create_image (bp, dltime, true);
653 display_image (bp->buffer);
655 logputs (LOG_VERBOSE, "\n\n");
661 /* This code attempts to maintain the notion of a "current" download
662 speed, over the course of no less than 3s. (Shorter intervals
663 produce very erratic results.)
665 To do so, it samples the speed in 150ms intervals and stores the
666 recorded samples in a FIFO history ring. The ring stores no more
667 than 20 intervals, hence the history covers the period of at least
668 three seconds and at most 20 reads into the past. This method
669 should produce reasonable results for downloads ranging from very
672 The idea is that for fast downloads, we get the speed over exactly
673 the last three seconds. For slow downloads (where a network read
674 takes more than 150ms to complete), we get the speed over a larger
675 time period, as large as it takes to complete thirty reads. This
676 is good because slow downloads tend to fluctuate more and a
677 3-second average would be too erratic. */
680 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
682 struct bar_progress_hist *hist = &bp->hist;
683 double recent_age = dltime - bp->recent_start;
685 /* Update the download count. */
686 bp->recent_bytes += howmuch;
688 /* For very small time intervals, we return after having updated the
689 "recent" download count. When its age reaches or exceeds minimum
690 sample time, it will be recorded in the history ring. */
691 if (recent_age < DLSPEED_SAMPLE_MIN)
696 /* If we're not downloading anything, we might be stalling,
697 i.e. not downloading anything for an extended period of time.
698 Since 0-reads do not enter the history ring, recent_age
699 effectively measures the time since last read. */
700 if (recent_age >= STALL_START_TIME)
702 /* If we're stalling, reset the ring contents because it's
703 stale and because it will make bar_update stop printing
704 the (bogus) current bandwidth. */
707 bp->recent_bytes = 0;
712 /* We now have a non-zero amount of to store to the speed ring. */
714 /* If the stall status was acquired, reset it. */
718 /* "recent_age" includes the entired stalled period, which
719 could be very long. Don't update the speed ring with that
720 value because the current bandwidth would start too small.
721 Start with an arbitrary (but more reasonable) time value and
726 /* Store "recent" bytes and download time to history ring at the
729 /* To correctly maintain the totals, first invalidate existing data
730 (least recent in time) at this position. */
731 hist->total_time -= hist->times[hist->pos];
732 hist->total_bytes -= hist->bytes[hist->pos];
734 /* Now store the new data and update the totals. */
735 hist->times[hist->pos] = recent_age;
736 hist->bytes[hist->pos] = bp->recent_bytes;
737 hist->total_time += recent_age;
738 hist->total_bytes += bp->recent_bytes;
740 /* Start a new "recent" period. */
741 bp->recent_start = dltime;
742 bp->recent_bytes = 0;
744 /* Advance the current ring position. */
745 if (++hist->pos == DLSPEED_HISTORY_SIZE)
749 /* Sledgehammer check to verify that the totals are accurate. */
752 double sumt = 0, sumb = 0;
753 for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
755 sumt += hist->times[i];
756 sumb += hist->bytes[i];
758 assert (sumb == hist->total_bytes);
759 /* We can't use assert(sumt==hist->total_time) because some
760 precision is lost by adding and subtracting floating-point
761 numbers. But during a download this precision should not be
762 detectable, i.e. no larger than 1ns. */
763 double diff = sumt - hist->total_time;
764 if (diff < 0) diff = -diff;
765 assert (diff < 1e-9);
770 #if USE_NLS_PROGRESS_BAR
772 count_cols (const char *mbs)
776 int remaining = strlen(mbs);
782 bytes = mbtowc (&wc, mbs, remaining);
783 assert (bytes != 0); /* Only happens when *mbs == '\0' */
786 /* Invalid sequence. We'll just have to fudge it. */
787 return cols + remaining;
791 wccols = wcwidth(wc);
792 cols += (wccols == -1? 1 : wccols);
797 # define count_cols(mbs) ((int)(strlen(mbs)))
803 /* TRANSLATORS: "ETA" is English-centric, but this must
804 be short, ideally 3 chars. Abbreviate if necessary. */
805 static const char eta_str[] = N_(" eta %s");
806 static const char *eta_trans;
807 static int bytes_cols_diff;
808 if (eta_trans == NULL)
813 #if USE_NLS_PROGRESS_BAR
814 eta_trans = _(eta_str);
819 /* Determine the number of bytes used in the translated string,
820 * versus the number of columns used. This is to figure out how
821 * many spaces to add at the end to pad to the full line width.
823 * We'll store the difference between the number of bytes and
824 * number of columns, so that removing this from the string length
825 * will reveal the total number of columns in the progress bar. */
826 nbytes = strlen (eta_trans);
827 ncols = count_cols (eta_trans);
828 bytes_cols_diff = nbytes - ncols;
832 *bcd = bytes_cols_diff;
837 #define APPEND_LITERAL(s) do { \
838 memcpy (p, s, sizeof (s) - 1); \
839 p += sizeof (s) - 1; \
842 /* Use move_to_end (s) to get S to point the end of the string (the
843 terminating \0). This is faster than s+=strlen(s), but some people
844 are confused when they see strchr (s, '\0') in the code. */
845 #define move_to_end(s) s = strchr (s, '\0');
848 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
852 create_image (struct bar_progress *bp, double dl_total_time, bool done)
854 char *p = bp->buffer;
855 wgint size = bp->initial_length + bp->count;
857 const char *size_grouped = with_thousand_seps (size);
858 int size_grouped_len = count_cols (size_grouped);
859 /* Difference between num cols and num bytes: */
860 int size_grouped_diff = strlen (size_grouped) - size_grouped_len;
861 int size_grouped_pad; /* Used to pad the field width for size_grouped. */
863 struct bar_progress_hist *hist = &bp->hist;
865 /* The progress bar should look like this:
866 xx% [=======> ] nn,nnn 12.34K/s eta 36m 51s
868 Calculate the geometry. The idea is to assign as much room as
869 possible to the progress bar. The other idea is to never let
870 things "jitter", i.e. pad elements that vary in size so that
871 their variance does not affect the placement of other elements.
872 It would be especially bad for the progress bar to be resized
875 "xx% " or "100%" - percentage - 4 chars
876 "[]" - progress bar decorations - 2 chars
877 " nnn,nnn,nnn" - downloaded bytes - 12 chars or very rarely more
878 " 12.5K/s" - download rate - 8 chars
879 " eta 36m 51s" - ETA - 14 chars
881 "=====>..." - progress bar - the rest
883 int dlbytes_size = 1 + MAX (size_grouped_len, 11);
884 int progress_size = bp->width - (4 + 2 + dlbytes_size + 8 + 14);
886 /* The difference between the number of bytes used,
887 and the number of columns used. */
888 int bytes_cols_diff = 0;
890 if (progress_size < 5)
894 if (bp->total_length > 0)
896 int percentage = 100.0 * size / bp->total_length;
897 assert (percentage <= 100);
899 if (percentage < 100)
900 sprintf (p, "%2d%% ", percentage);
906 APPEND_LITERAL (" ");
908 /* The progress bar: "[====> ]" or "[++==> ]". */
909 if (progress_size && bp->total_length > 0)
911 /* Size of the initial portion. */
912 int insz = (double)bp->initial_length / bp->total_length * progress_size;
914 /* Size of the downloaded portion. */
915 int dlsz = (double)size / bp->total_length * progress_size;
920 assert (dlsz <= progress_size);
921 assert (insz <= dlsz);
926 /* Print the initial portion of the download with '+' chars, the
927 rest with '=' and one '>'. */
928 for (i = 0; i < insz; i++)
933 for (i = 0; i < dlsz - 1; i++)
938 while (p - begin < progress_size)
942 else if (progress_size)
944 /* If we can't draw a real progress bar, then at least show
945 *something* to the user. */
946 int ind = bp->tick % (progress_size * 2 - 6);
949 /* Make the star move in two directions. */
950 if (ind < progress_size - 2)
953 pos = progress_size - (ind - progress_size + 5);
956 for (i = 0; i < progress_size; i++)
958 if (i == pos - 1) *p++ = '<';
959 else if (i == pos ) *p++ = '=';
960 else if (i == pos + 1) *p++ = '>';
970 sprintf (p, " %s", size_grouped);
972 /* Pad with spaces to 11 chars for the size_grouped field;
973 * couldn't use the field width specifier in sprintf, because
974 * it counts in bytes, not characters. */
975 for (size_grouped_pad = 11 - size_grouped_len;
976 size_grouped_pad > 0;
983 if (hist->total_time > 0 && hist->total_bytes)
985 static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" };
987 /* Calculate the download speed using the history ring and
988 recent data that hasn't made it to the ring yet. */
989 wgint dlquant = hist->total_bytes + bp->recent_bytes;
990 double dltime = hist->total_time + (dl_total_time - bp->recent_start);
991 double dlspeed = calc_rate (dlquant, dltime, &units);
992 sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
993 dlspeed, short_units[units]);
997 APPEND_LITERAL (" --.-K/s");
1001 /* " eta ..m ..s"; wait for three seconds before displaying the ETA.
1002 That's because the ETA value needs a while to become
1004 if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
1008 /* Don't change the value of ETA more than approximately once
1009 per second; doing so would cause flashing without providing
1010 any value to the user. */
1011 if (bp->total_length != size
1012 && bp->last_eta_value != 0
1013 && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
1014 eta = bp->last_eta_value;
1017 /* Calculate ETA using the average download speed to predict
1018 the future speed. If you want to use a speed averaged
1019 over a more recent period, replace dl_total_time with
1020 hist->total_time and bp->count with hist->total_bytes.
1021 I found that doing that results in a very jerky and
1022 ultimately unreliable ETA. */
1023 wgint bytes_remaining = bp->total_length - size;
1024 double eta_ = dl_total_time * bytes_remaining / bp->count;
1025 if (eta_ >= INT_MAX - 1)
1027 eta = (int) (eta_ + 0.5);
1028 bp->last_eta_value = eta;
1029 bp->last_eta_time = dl_total_time;
1032 sprintf (p, get_eta(&bytes_cols_diff),
1033 eta_to_human_short (eta, false));
1036 else if (bp->total_length > 0)
1039 APPEND_LITERAL (" ");
1044 /* When the download is done, print the elapsed time. */
1048 /* Note to translators: this should not take up more room than
1049 available here. Abbreviate if necessary. */
1050 strcpy (p, _(" in "));
1051 nbytes = strlen (p);
1052 ncols = count_cols (p);
1053 bytes_cols_diff = nbytes - ncols;
1055 if (dl_total_time >= 10)
1056 strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
1058 sprintf (p, "%ss", print_decimal (dl_total_time));
1062 while (p - bp->buffer - bytes_cols_diff - size_grouped_diff < bp->width)
1067 /* Print the contents of the buffer as a one-line ASCII "image" so
1068 that it can be overwritten next time. */
1071 display_image (char *buf)
1073 bool old = log_set_save_context (false);
1074 logputs (LOG_VERBOSE, "\r");
1075 logputs (LOG_VERBOSE, buf);
1076 log_set_save_context (old);
1080 bar_set_params (const char *params)
1082 char *term = getenv ("TERM");
1085 && 0 == strcmp (params, "force"))
1086 current_impl_locked = 1;
1090 /* The progress bar doesn't make sense if the output is not a
1091 TTY -- when logging to file, it is better to review the
1093 || !isatty (fileno (stderr))
1095 /* Normally we don't depend on terminal type because the
1096 progress bar only uses ^M to move the cursor to the
1097 beginning of line, which works even on dumb terminals. But
1098 Jamie Zawinski reports that ^M and ^H tricks don't work in
1099 Emacs shell buffers, and only make a mess. */
1100 || (term && 0 == strcmp (term, "emacs"))
1102 && !current_impl_locked)
1104 /* We're not printing to a TTY, so revert to the fallback
1105 display. #### We're recursively calling
1106 set_progress_implementation here, which is slightly kludgy.
1107 It would be nicer if we provided that function a return value
1108 indicating a failure of some sort. */
1109 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1116 progress_handle_sigwinch (int sig)
1118 received_sigwinch = 1;
1119 signal (SIGWINCH, progress_handle_sigwinch);
1123 /* Provide a short human-readable rendition of the ETA. This is like
1124 secs_to_human_time in main.c, except the output doesn't include
1125 fractions (which would look silly in by nature imprecise ETA) and
1126 takes less room. If the time is measured in hours, hours and
1127 minutes (but not seconds) are shown; if measured in days, then days
1128 and hours are shown. This ensures brevity while still displaying
1129 as much as possible.
1131 If CONDENSED is true, the separator between minutes and seconds
1132 (and hours and minutes, etc.) is not included, shortening the
1133 display by one additional character. This is used for dot
1136 The display never occupies more than 7 characters of screen
1140 eta_to_human_short (int secs, bool condensed)
1142 static char buf[10]; /* 8 should be enough, but just in case */
1143 static int last = -1;
1144 const char *space = condensed ? "" : " ";
1146 /* Trivial optimization. create_image can call us every 200 msecs
1147 (see bar_update) for fast downloads, but ETA will only change
1148 once per 900 msecs. */
1154 sprintf (buf, "%ds", secs);
1155 else if (secs < 100 * 60)
1156 sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1157 else if (secs < 48 * 3600)
1158 sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1159 else if (secs < 100 * 86400)
1160 sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 24);
1162 /* even (2^31-1)/86400 doesn't overflow BUF. */
1163 sprintf (buf, "%dd", secs / 86400);