2 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007,
3 2008 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 int namelen = colon ? 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 ? 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 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);
771 #define wcwidth(wc) (1)
775 count_cols (const char *mbs)
779 int remaining = strlen(mbs);
784 bytes = mbtowc (&wc, mbs, remaining);
792 /* Translation note: "ETA" is English-centric, but this must
793 be short, ideally 3 chars. Abbreviate if necessary. */
794 static const char eta_str[] = N_(" eta %s");
795 static const char *eta_trans;
796 static int bytes_cols_diff;
801 if (eta_trans == NULL)
806 eta_trans = _(eta_str);
808 /* Determine the number of bytes used in the translated string,
809 * versus the number of columns used. This is to figure out how
810 * many spaces to add at the end to pad to the full line width.
812 * We'll store the difference between the number of bytes and
813 * number of columns, so that removing this from the string length
814 * will reveal the total number of columns in the progress bar. */
815 nbytes = strlen (eta_trans);
816 ncols = count_cols (eta_trans);
817 bytes_cols_diff = nbytes - ncols;
823 #define APPEND_LITERAL(s) do { \
824 memcpy (p, s, sizeof (s) - 1); \
825 p += sizeof (s) - 1; \
828 /* Use move_to_end (s) to get S to point the end of the string (the
829 terminating \0). This is faster than s+=strlen(s), but some people
830 are confused when they see strchr (s, '\0') in the code. */
831 #define move_to_end(s) s = strchr (s, '\0');
834 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
838 create_image (struct bar_progress *bp, double dl_total_time, bool done)
840 char *p = bp->buffer;
841 wgint size = bp->initial_length + bp->count;
843 const char *size_grouped = with_thousand_seps (size);
844 int size_grouped_len = count_cols (size_grouped);
845 /* Difference between num cols and num bytes: */
846 int size_grouped_diff = strlen (size_grouped) - size_grouped_len;
847 int size_grouped_pad; /* Used to pad the field width for size_grouped. */
849 struct bar_progress_hist *hist = &bp->hist;
851 /* The progress bar should look like this:
852 xx% [=======> ] nn,nnn 12.34K/s eta 36m 51s
854 Calculate the geometry. The idea is to assign as much room as
855 possible to the progress bar. The other idea is to never let
856 things "jitter", i.e. pad elements that vary in size so that
857 their variance does not affect the placement of other elements.
858 It would be especially bad for the progress bar to be resized
861 "xx% " or "100%" - percentage - 4 chars
862 "[]" - progress bar decorations - 2 chars
863 " nnn,nnn,nnn" - downloaded bytes - 12 chars or very rarely more
864 " 12.5K/s" - download rate - 8 chars
865 " eta 36m 51s" - ETA - 13 chars
867 "=====>..." - progress bar - the rest
869 int dlbytes_size = 1 + MAX (size_grouped_len, 11);
870 int progress_size = bp->width - (4 + 2 + dlbytes_size + 8 + 13);
872 if (progress_size < 5)
876 if (bp->total_length > 0)
878 int percentage = 100.0 * size / bp->total_length;
879 assert (percentage <= 100);
881 if (percentage < 100)
882 sprintf (p, "%2d%% ", percentage);
888 APPEND_LITERAL (" ");
890 /* The progress bar: "[====> ]" or "[++==> ]". */
891 if (progress_size && bp->total_length > 0)
893 /* Size of the initial portion. */
894 int insz = (double)bp->initial_length / bp->total_length * progress_size;
896 /* Size of the downloaded portion. */
897 int dlsz = (double)size / bp->total_length * progress_size;
902 assert (dlsz <= progress_size);
903 assert (insz <= dlsz);
908 /* Print the initial portion of the download with '+' chars, the
909 rest with '=' and one '>'. */
910 for (i = 0; i < insz; i++)
915 for (i = 0; i < dlsz - 1; i++)
920 while (p - begin < progress_size)
924 else if (progress_size)
926 /* If we can't draw a real progress bar, then at least show
927 *something* to the user. */
928 int ind = bp->tick % (progress_size * 2 - 6);
931 /* Make the star move in two directions. */
932 if (ind < progress_size - 2)
935 pos = progress_size - (ind - progress_size + 5);
938 for (i = 0; i < progress_size; i++)
940 if (i == pos - 1) *p++ = '<';
941 else if (i == pos ) *p++ = '=';
942 else if (i == pos + 1) *p++ = '>';
952 sprintf (p, " %s", size_grouped);
954 /* Pad with spaces to 11 chars for the size_grouped field;
955 * couldn't use the field width specifier in sprintf, because
956 * it counts in bytes, not characters. */
957 for (size_grouped_pad = 11 - size_grouped_len;
958 size_grouped_pad > 0;
965 if (hist->total_time > 0 && hist->total_bytes)
967 static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" };
969 /* Calculate the download speed using the history ring and
970 recent data that hasn't made it to the ring yet. */
971 wgint dlquant = hist->total_bytes + bp->recent_bytes;
972 double dltime = hist->total_time + (dl_total_time - bp->recent_start);
973 double dlspeed = calc_rate (dlquant, dltime, &units);
974 sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
975 dlspeed, short_units[units]);
979 APPEND_LITERAL (" --.-K/s");
983 /* " eta ..m ..s"; wait for three seconds before displaying the ETA.
984 That's because the ETA value needs a while to become
986 if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
990 /* Don't change the value of ETA more than approximately once
991 per second; doing so would cause flashing without providing
992 any value to the user. */
993 if (bp->total_length != size
994 && bp->last_eta_value != 0
995 && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
996 eta = bp->last_eta_value;
999 /* Calculate ETA using the average download speed to predict
1000 the future speed. If you want to use a speed averaged
1001 over a more recent period, replace dl_total_time with
1002 hist->total_time and bp->count with hist->total_bytes.
1003 I found that doing that results in a very jerky and
1004 ultimately unreliable ETA. */
1005 wgint bytes_remaining = bp->total_length - size;
1006 double eta_ = dl_total_time * bytes_remaining / bp->count;
1007 if (eta_ >= INT_MAX - 1)
1009 eta = (int) (eta_ + 0.5);
1010 bp->last_eta_value = eta;
1011 bp->last_eta_time = dl_total_time;
1014 sprintf (p, get_eta(), eta_to_human_short (eta, false));
1017 else if (bp->total_length > 0)
1020 APPEND_LITERAL (" ");
1025 /* When the download is done, print the elapsed time. */
1027 /* Note to translators: this should not take up more room than
1028 available here. Abbreviate if necessary. */
1029 strcpy (p, _(" in "));
1030 move_to_end (p); /* not p+=6, think translations! */
1031 if (dl_total_time >= 10)
1032 strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
1034 sprintf (p, "%ss", print_decimal (dl_total_time));
1038 assert (p - bp->buffer - bytes_cols_diff - size_grouped_diff <= bp->width);
1040 while (p - bp->buffer - bytes_cols_diff - size_grouped_diff < bp->width)
1045 /* Print the contents of the buffer as a one-line ASCII "image" so
1046 that it can be overwritten next time. */
1049 display_image (char *buf)
1051 bool old = log_set_save_context (false);
1052 logputs (LOG_VERBOSE, "\r");
1053 logputs (LOG_VERBOSE, buf);
1054 log_set_save_context (old);
1058 bar_set_params (const char *params)
1060 char *term = getenv ("TERM");
1063 && 0 == strcmp (params, "force"))
1064 current_impl_locked = 1;
1068 /* The progress bar doesn't make sense if the output is not a
1069 TTY -- when logging to file, it is better to review the
1071 || !isatty (fileno (stderr))
1073 /* Normally we don't depend on terminal type because the
1074 progress bar only uses ^M to move the cursor to the
1075 beginning of line, which works even on dumb terminals. But
1076 Jamie Zawinski reports that ^M and ^H tricks don't work in
1077 Emacs shell buffers, and only make a mess. */
1078 || (term && 0 == strcmp (term, "emacs"))
1080 && !current_impl_locked)
1082 /* We're not printing to a TTY, so revert to the fallback
1083 display. #### We're recursively calling
1084 set_progress_implementation here, which is slightly kludgy.
1085 It would be nicer if we provided that function a return value
1086 indicating a failure of some sort. */
1087 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1094 progress_handle_sigwinch (int sig)
1096 received_sigwinch = 1;
1097 signal (SIGWINCH, progress_handle_sigwinch);
1101 /* Provide a short human-readable rendition of the ETA. This is like
1102 secs_to_human_time in main.c, except the output doesn't include
1103 fractions (which would look silly in by nature imprecise ETA) and
1104 takes less room. If the time is measured in hours, hours and
1105 minutes (but not seconds) are shown; if measured in days, then days
1106 and hours are shown. This ensures brevity while still displaying
1107 as much as possible.
1109 If CONDENSED is true, the separator between minutes and seconds
1110 (and hours and minutes, etc.) is not included, shortening the
1111 display by one additional character. This is used for dot
1114 The display never occupies more than 7 characters of screen
1118 eta_to_human_short (int secs, bool condensed)
1120 static char buf[10]; /* 8 should be enough, but just in case */
1121 static int last = -1;
1122 const char *space = condensed ? "" : " ";
1124 /* Trivial optimization. create_image can call us every 200 msecs
1125 (see bar_update) for fast downloads, but ETA will only change
1126 once per 900 msecs. */
1132 sprintf (buf, "%ds", secs);
1133 else if (secs < 100 * 60)
1134 sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1135 else if (secs < 48 * 3600)
1136 sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1137 else if (secs < 100 * 86400)
1138 sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 60);
1140 /* even (2^31-1)/86400 doesn't overflow BUF. */
1141 sprintf (buf, "%dd", secs / 86400);