2 Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
3 2010, 2011 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. */
47 struct progress_implementation {
50 void *(*create) (wgint, wgint);
51 void (*update) (void *, wgint, double);
52 void (*draw) (void *);
53 void (*finish) (void *, double);
54 void (*set_params) (const char *);
57 /* Necessary forward declarations. */
59 static void *dot_create (wgint, wgint);
60 static void dot_update (void *, wgint, double);
61 static void dot_finish (void *, double);
62 static void dot_draw (void *);
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_draw (void *);
68 static void bar_finish (void *, double);
69 static void bar_set_params (const char *);
71 static struct progress_implementation implementations[] = {
72 { "dot", 0, dot_create, dot_update, dot_draw, dot_finish, dot_set_params },
73 { "bar", 1, bar_create, bar_update, bar_draw, bar_finish, bar_set_params }
75 static struct progress_implementation *current_impl;
76 static int current_impl_locked;
78 /* Progress implementation used by default. Can be overriden in
79 wgetrc or by the fallback one. */
81 #define DEFAULT_PROGRESS_IMPLEMENTATION "bar"
83 /* Fallback progress implementation should be something that works
84 under all display types. If you put something other than "dot"
85 here, remember that bar_set_params tries to switch to this if we're
86 not running on a TTY. So changing this to "bar" could cause
89 #define FALLBACK_PROGRESS_IMPLEMENTATION "dot"
91 /* Return true if NAME names a valid progress bar implementation. The
92 characters after the first : will be ignored. */
95 valid_progress_implementation_p (const char *name)
98 struct progress_implementation *pi = implementations;
99 char *colon = strchr (name, ':');
100 size_t namelen = colon ? (size_t) (colon - name) : strlen (name);
102 for (i = 0; i < countof (implementations); i++, pi++)
103 if (!strncmp (pi->name, name, namelen))
108 /* Set the progress implementation to NAME. */
111 set_progress_implementation (const char *name)
114 struct progress_implementation *pi = implementations;
118 name = DEFAULT_PROGRESS_IMPLEMENTATION;
120 colon = strchr (name, ':');
121 namelen = colon ? (size_t) (colon - name) : strlen (name);
123 for (i = 0; i < countof (implementations); i++, pi++)
124 if (!strncmp (pi->name, name, namelen))
127 current_impl_locked = 0;
130 /* We call pi->set_params even if colon is NULL because we
131 want to give the implementation a chance to set up some
132 things it needs to run. */
136 pi->set_params (colon);
142 static int output_redirected;
145 progress_schedule_redirect (void)
147 output_redirected = 1;
150 /* Create a progress gauge. INITIAL is the number of bytes the
151 download starts from (zero if the download starts from scratch).
152 TOTAL is the expected total number of bytes in this download. If
153 TOTAL is zero, it means that the download size is not known in
157 progress_create (wgint initial, wgint total)
159 /* Check if the log status has changed under our feet. */
160 if (output_redirected)
162 if (!current_impl_locked)
163 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
164 output_redirected = 0;
167 return current_impl->create (initial, total);
170 /* Return true if the progress gauge is "interactive", i.e. if it can
171 profit from being called regularly even in absence of data. The
172 progress bar is interactive because it regularly updates the ETA
173 and current update. */
176 progress_interactive_p (void *progress)
178 return current_impl->interactive;
181 /* Inform the progress gauge of newly received bytes. DLTIME is the
182 time since the beginning of the download. */
185 progress_update (void *progress, wgint howmuch, double dltime)
187 current_impl->update (progress, howmuch, dltime);
188 current_impl->draw (progress);
191 /* Tell the progress gauge to clean up. Calling this will free the
192 PROGRESS object, the further use of which is not allowed. */
195 progress_finish (void *progress, double dltime)
197 current_impl->finish (progress, dltime);
202 struct dot_progress {
203 wgint initial_length; /* how many bytes have been downloaded
205 wgint total_length; /* expected total byte count when the
208 int accumulated; /* number of bytes accumulated after
209 the last printed dot */
211 double dltime; /* download time so far */
212 int rows; /* number of rows printed so far */
213 int dots; /* number of dots printed in this row */
215 double last_timer_value;
218 /* Dot-progress backend for progress_create. */
221 dot_create (wgint initial, wgint total)
223 struct dot_progress *dp = xnew0 (struct dot_progress);
224 dp->initial_length = initial;
225 dp->total_length = total;
227 if (dp->initial_length)
229 int dot_bytes = opt.dot_bytes;
230 const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
232 int remainder = dp->initial_length % ROW_BYTES;
233 wgint skipped = dp->initial_length - remainder;
237 wgint skipped_k = skipped / 1024; /* skipped amount in K */
238 int skipped_k_len = numdigit (skipped_k);
239 if (skipped_k_len < 6)
242 /* Align the [ skipping ... ] line with the dots. To do
243 that, insert the number of spaces equal to the number of
244 digits in the skipped amount in K. */
245 logprintf (LOG_VERBOSE, _("\n%*s[ skipping %sK ]"),
246 2 + skipped_k_len, "",
247 number_to_static_string (skipped_k));
250 logprintf (LOG_VERBOSE, "\n%6sK",
251 number_to_static_string (skipped / 1024));
252 for (; remainder >= dot_bytes; remainder -= dot_bytes)
254 if (dp->dots % opt.dot_spacing == 0)
255 logputs (LOG_VERBOSE, " ");
256 logputs (LOG_VERBOSE, ",");
259 assert (dp->dots < opt.dots_in_line);
261 dp->accumulated = remainder;
262 dp->rows = skipped / ROW_BYTES;
268 static const char *eta_to_human_short (int, bool);
270 /* Prints the stats (percentage of completion, speed, ETA) for current
271 row. DLTIME is the time spent downloading the data in current
274 #### This function is somewhat uglified by the fact that current
275 row and last row have somewhat different stats requirements. It
276 might be worthwhile to split it to two different functions. */
279 print_row_stats (struct dot_progress *dp, double dltime, bool last)
281 const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
283 /* bytes_displayed is the number of bytes indicated to the user by
284 dots printed so far, includes the initially "skipped" amount */
285 wgint bytes_displayed = dp->rows * ROW_BYTES + dp->dots * opt.dot_bytes;
288 /* For last row also count bytes accumulated after last dot */
289 bytes_displayed += dp->accumulated;
291 if (dp->total_length)
293 /* Round to floor value to provide gauge how much data *has*
294 been retrieved. 12.8% will round to 12% because the 13% mark
295 has not yet been reached. 100% is only shown when done. */
296 int percentage = 100.0 * bytes_displayed / dp->total_length;
297 logprintf (LOG_VERBOSE, "%3d%%", percentage);
301 static char names[] = {' ', 'K', 'M', 'G'};
304 wgint bytes_this_row;
306 bytes_this_row = ROW_BYTES;
308 /* For last row also include bytes accumulated after last dot. */
309 bytes_this_row = dp->dots * opt.dot_bytes + dp->accumulated;
310 /* Don't count the portion of the row belonging to initial_length */
311 if (dp->rows == dp->initial_length / ROW_BYTES)
312 bytes_this_row -= dp->initial_length % ROW_BYTES;
313 rate = calc_rate (bytes_this_row, dltime - dp->last_timer_value, &units);
314 logprintf (LOG_VERBOSE, " %4.*f%c",
315 rate >= 99.95 ? 0 : rate >= 9.995 ? 1 : 2,
317 dp->last_timer_value = dltime;
322 /* Display ETA based on average speed. Inspired by Vladi
323 Belperchinov-Shabanski's "wget-new-percentage" patch. */
324 if (dp->total_length)
326 wgint bytes_remaining = dp->total_length - bytes_displayed;
327 /* The quantity downloaded in this download run. */
328 wgint bytes_sofar = bytes_displayed - dp->initial_length;
329 double eta = dltime * bytes_remaining / bytes_sofar;
330 if (eta < INT_MAX - 1)
331 logprintf (LOG_VERBOSE, " %s",
332 eta_to_human_short ((int) (eta + 0.5), true));
337 /* When done, print the total download time */
339 logprintf (LOG_VERBOSE, "=%s",
340 eta_to_human_short ((int) (dltime + 0.5), true));
342 logprintf (LOG_VERBOSE, "=%ss", print_decimal (dltime));
346 /* Dot-progress backend for progress_update. */
349 dot_update (void *progress, wgint howmuch, double dltime)
351 struct dot_progress *dp = progress;
352 dp->accumulated += howmuch;
357 dot_draw (void *progress)
359 struct dot_progress *dp = progress;
360 int dot_bytes = opt.dot_bytes;
361 wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
363 log_set_flush (false);
365 for (; dp->accumulated >= dot_bytes; dp->accumulated -= dot_bytes)
368 logprintf (LOG_VERBOSE, "\n%6sK",
369 number_to_static_string (dp->rows * ROW_BYTES / 1024));
371 if (dp->dots % opt.dot_spacing == 0)
372 logputs (LOG_VERBOSE, " ");
373 logputs (LOG_VERBOSE, ".");
376 if (dp->dots >= opt.dots_in_line)
381 print_row_stats (dp, dp->dltime, false);
385 log_set_flush (true);
388 /* Dot-progress backend for progress_finish. */
391 dot_finish (void *progress, double dltime)
393 struct dot_progress *dp = progress;
394 wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
397 log_set_flush (false);
400 logprintf (LOG_VERBOSE, "\n%6sK",
401 number_to_static_string (dp->rows * ROW_BYTES / 1024));
402 for (i = dp->dots; i < opt.dots_in_line; i++)
404 if (i % opt.dot_spacing == 0)
405 logputs (LOG_VERBOSE, " ");
406 logputs (LOG_VERBOSE, " ");
409 print_row_stats (dp, dltime, true);
410 logputs (LOG_VERBOSE, "\n\n");
411 log_set_flush (false);
416 /* This function interprets the progress "parameters". For example,
417 if Wget is invoked with --progress=dot:mega, it will set the
418 "dot-style" to "mega". Valid styles are default, binary, mega, and
422 dot_set_params (const char *params)
424 if (!params || !*params)
425 params = opt.dot_style;
430 /* We use this to set the retrieval style. */
431 if (!strcasecmp (params, "default"))
433 /* Default style: 1K dots, 10 dots in a cluster, 50 dots in a
435 opt.dot_bytes = 1024;
436 opt.dot_spacing = 10;
437 opt.dots_in_line = 50;
439 else if (!strcasecmp (params, "binary"))
441 /* "Binary" retrieval: 8K dots, 16 dots in a cluster, 48 dots
443 opt.dot_bytes = 8192;
444 opt.dot_spacing = 16;
445 opt.dots_in_line = 48;
447 else if (!strcasecmp (params, "mega"))
449 /* "Mega" retrieval, for retrieving very long files; each dot is
450 64K, 8 dots in a cluster, 6 clusters (3M) in a line. */
451 opt.dot_bytes = 65536L;
453 opt.dots_in_line = 48;
455 else if (!strcasecmp (params, "giga"))
457 /* "Giga" retrieval, for retrieving very very *very* long files;
458 each dot is 1M, 8 dots in a cluster, 4 clusters (32M) in a
460 opt.dot_bytes = (1L << 20);
462 opt.dots_in_line = 32;
466 _("Invalid dot style specification %s; leaving unchanged.\n"),
470 /* "Thermometer" (bar) progress. */
472 /* Assumed screen width if we can't find the real value. */
473 #define DEFAULT_SCREEN_WIDTH 80
475 /* Minimum screen width we'll try to work with. If this is too small,
476 create_image will overflow the buffer. */
477 #define MINIMUM_SCREEN_WIDTH 45
479 /* The last known screen width. This can be updated by the code that
480 detects that SIGWINCH was received (but it's never updated from the
482 static int screen_width;
484 /* A flag that, when set, means SIGWINCH was received. */
485 static volatile sig_atomic_t received_sigwinch;
487 /* Size of the download speed history ring. */
488 #define DLSPEED_HISTORY_SIZE 20
490 /* The minimum time length of a history sample. By default, each
491 sample is at least 150ms long, which means that, over the course of
492 20 samples, "current" download speed spans at least 3s into the
494 #define DLSPEED_SAMPLE_MIN 0.15
496 /* The time after which the download starts to be considered
497 "stalled", i.e. the current bandwidth is not printed and the recent
498 download speeds are scratched. */
499 #define STALL_START_TIME 5
501 /* Time between screen refreshes will not be shorter than this, so
502 that Wget doesn't swamp the TTY with output. */
503 #define REFRESH_INTERVAL 0.2
505 /* Don't refresh the ETA too often to avoid jerkiness in predictions.
506 This allows ETA to change approximately once per second. */
507 #define ETA_REFRESH_INTERVAL 0.99
509 struct bar_progress {
510 wgint initial_length; /* how many bytes have been downloaded
512 wgint total_length; /* expected total byte count when the
514 wgint count; /* bytes downloaded so far */
516 double last_screen_update; /* time of the last screen update,
517 measured since the beginning of
520 double dltime; /* download time so far */
521 int width; /* screen width we're using at the
522 time the progress gauge was
523 created. this is different from
524 the screen_width global variable in
525 that the latter can be changed by a
527 char *buffer; /* buffer where the bar "image" is
529 int tick; /* counter used for drawing the
530 progress bar where the total size
533 /* The following variables (kept in a struct for namespace reasons)
534 keep track of recent download speeds. See bar_update() for
536 struct bar_progress_hist {
538 double times[DLSPEED_HISTORY_SIZE];
539 wgint bytes[DLSPEED_HISTORY_SIZE];
541 /* The sum of times and bytes respectively, maintained for
547 double recent_start; /* timestamp of beginning of current
549 wgint recent_bytes; /* bytes downloaded so far. */
551 bool stalled; /* set when no data arrives for longer
552 than STALL_START_TIME, then reset
553 when new data arrives. */
555 /* create_image() uses these to make sure that ETA information
557 double last_eta_time; /* time of the last update to download
558 speed and ETA, measured since the
559 beginning of download. */
563 static void create_image (struct bar_progress *, double, bool);
564 static void display_image (char *);
567 bar_create (wgint initial, wgint total)
569 struct bar_progress *bp = xnew0 (struct bar_progress);
571 /* In theory, our callers should take care of this pathological
572 case, but it can sometimes happen. */
576 bp->initial_length = initial;
577 bp->total_length = total;
579 /* Initialize screen_width if this hasn't been done or if it might
580 have changed, as indicated by receiving SIGWINCH. */
581 if (!screen_width || received_sigwinch)
583 screen_width = determine_screen_width ();
585 screen_width = DEFAULT_SCREEN_WIDTH;
586 else if (screen_width < MINIMUM_SCREEN_WIDTH)
587 screen_width = MINIMUM_SCREEN_WIDTH;
588 received_sigwinch = 0;
591 /* - 1 because we don't want to use the last screen column. */
592 bp->width = screen_width - 1;
593 /* + enough space for the terminating zero, and hopefully enough room
594 * for multibyte characters. */
595 bp->buffer = xmalloc (bp->width + 100);
597 logputs (LOG_VERBOSE, "\n");
599 create_image (bp, 0, false);
600 display_image (bp->buffer);
605 static void update_speed_ring (struct bar_progress *, wgint, double);
608 bar_update (void *progress, wgint howmuch, double dltime)
610 struct bar_progress *bp = progress;
613 bp->count += howmuch;
614 if (bp->total_length > 0
615 && bp->count + bp->initial_length > bp->total_length)
616 /* We could be downloading more than total_length, e.g. when the
617 server sends an incorrect Content-Length header. In that case,
618 adjust bp->total_length to the new reality, so that the code in
619 create_image() that depends on total size being smaller or
620 equal to the expected size doesn't abort. */
621 bp->total_length = bp->initial_length + bp->count;
623 update_speed_ring (bp, howmuch, dltime);
627 bar_draw (void *progress)
629 bool force_screen_update = false;
630 struct bar_progress *bp = progress;
632 /* If SIGWINCH (the window size change signal) been received,
633 determine the new screen size and update the screen. */
634 if (received_sigwinch)
636 int old_width = screen_width;
637 screen_width = determine_screen_width ();
639 screen_width = DEFAULT_SCREEN_WIDTH;
640 else if (screen_width < MINIMUM_SCREEN_WIDTH)
641 screen_width = MINIMUM_SCREEN_WIDTH;
642 if (screen_width != old_width)
644 bp->width = screen_width - 1;
645 bp->buffer = xrealloc (bp->buffer, bp->width + 100);
646 force_screen_update = true;
648 received_sigwinch = 0;
651 if (bp->dltime - bp->last_screen_update < REFRESH_INTERVAL && !force_screen_update)
652 /* Don't update more often than five times per second. */
655 create_image (bp, bp->dltime, false);
656 display_image (bp->buffer);
657 bp->last_screen_update = bp->dltime;
661 bar_finish (void *progress, double dltime)
663 struct bar_progress *bp = progress;
665 if (bp->total_length > 0
666 && bp->count + bp->initial_length > bp->total_length)
667 /* See bar_update() for explanation. */
668 bp->total_length = bp->initial_length + bp->count;
670 create_image (bp, dltime, true);
671 display_image (bp->buffer);
673 logputs (LOG_VERBOSE, "\n\n");
679 /* This code attempts to maintain the notion of a "current" download
680 speed, over the course of no less than 3s. (Shorter intervals
681 produce very erratic results.)
683 To do so, it samples the speed in 150ms intervals and stores the
684 recorded samples in a FIFO history ring. The ring stores no more
685 than 20 intervals, hence the history covers the period of at least
686 three seconds and at most 20 reads into the past. This method
687 should produce reasonable results for downloads ranging from very
690 The idea is that for fast downloads, we get the speed over exactly
691 the last three seconds. For slow downloads (where a network read
692 takes more than 150ms to complete), we get the speed over a larger
693 time period, as large as it takes to complete thirty reads. This
694 is good because slow downloads tend to fluctuate more and a
695 3-second average would be too erratic. */
698 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
700 struct bar_progress_hist *hist = &bp->hist;
701 double recent_age = dltime - bp->recent_start;
703 /* Update the download count. */
704 bp->recent_bytes += howmuch;
706 /* For very small time intervals, we return after having updated the
707 "recent" download count. When its age reaches or exceeds minimum
708 sample time, it will be recorded in the history ring. */
709 if (recent_age < DLSPEED_SAMPLE_MIN)
714 /* If we're not downloading anything, we might be stalling,
715 i.e. not downloading anything for an extended period of time.
716 Since 0-reads do not enter the history ring, recent_age
717 effectively measures the time since last read. */
718 if (recent_age >= STALL_START_TIME)
720 /* If we're stalling, reset the ring contents because it's
721 stale and because it will make bar_update stop printing
722 the (bogus) current bandwidth. */
725 bp->recent_bytes = 0;
730 /* We now have a non-zero amount of to store to the speed ring. */
732 /* If the stall status was acquired, reset it. */
736 /* "recent_age" includes the entired stalled period, which
737 could be very long. Don't update the speed ring with that
738 value because the current bandwidth would start too small.
739 Start with an arbitrary (but more reasonable) time value and
744 /* Store "recent" bytes and download time to history ring at the
747 /* To correctly maintain the totals, first invalidate existing data
748 (least recent in time) at this position. */
749 hist->total_time -= hist->times[hist->pos];
750 hist->total_bytes -= hist->bytes[hist->pos];
752 /* Now store the new data and update the totals. */
753 hist->times[hist->pos] = recent_age;
754 hist->bytes[hist->pos] = bp->recent_bytes;
755 hist->total_time += recent_age;
756 hist->total_bytes += bp->recent_bytes;
758 /* Start a new "recent" period. */
759 bp->recent_start = dltime;
760 bp->recent_bytes = 0;
762 /* Advance the current ring position. */
763 if (++hist->pos == DLSPEED_HISTORY_SIZE)
767 /* Sledgehammer check to verify that the totals are accurate. */
770 double sumt = 0, sumb = 0;
771 for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
773 sumt += hist->times[i];
774 sumb += hist->bytes[i];
776 assert (sumb == hist->total_bytes);
777 /* We can't use assert(sumt==hist->total_time) because some
778 precision is lost by adding and subtracting floating-point
779 numbers. But during a download this precision should not be
780 detectable, i.e. no larger than 1ns. */
781 double diff = sumt - hist->total_time;
782 if (diff < 0) diff = -diff;
783 assert (diff < 1e-9);
788 #if USE_NLS_PROGRESS_BAR
790 count_cols (const char *mbs)
794 int remaining = strlen(mbs);
800 bytes = mbtowc (&wc, mbs, remaining);
801 assert (bytes != 0); /* Only happens when *mbs == '\0' */
804 /* Invalid sequence. We'll just have to fudge it. */
805 return cols + remaining;
809 wccols = wcwidth(wc);
810 cols += (wccols == -1? 1 : wccols);
815 # define count_cols(mbs) ((int)(strlen(mbs)))
821 /* TRANSLATORS: "ETA" is English-centric, but this must
822 be short, ideally 3 chars. Abbreviate if necessary. */
823 static const char eta_str[] = N_(" eta %s");
824 static const char *eta_trans;
825 static int bytes_cols_diff;
826 if (eta_trans == NULL)
831 #if USE_NLS_PROGRESS_BAR
832 eta_trans = _(eta_str);
837 /* Determine the number of bytes used in the translated string,
838 * versus the number of columns used. This is to figure out how
839 * many spaces to add at the end to pad to the full line width.
841 * We'll store the difference between the number of bytes and
842 * number of columns, so that removing this from the string length
843 * will reveal the total number of columns in the progress bar. */
844 nbytes = strlen (eta_trans);
845 ncols = count_cols (eta_trans);
846 bytes_cols_diff = nbytes - ncols;
850 *bcd = bytes_cols_diff;
855 #define APPEND_LITERAL(s) do { \
856 memcpy (p, s, sizeof (s) - 1); \
857 p += sizeof (s) - 1; \
860 /* Use move_to_end (s) to get S to point the end of the string (the
861 terminating \0). This is faster than s+=strlen(s), but some people
862 are confused when they see strchr (s, '\0') in the code. */
863 #define move_to_end(s) s = strchr (s, '\0');
866 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
870 create_image (struct bar_progress *bp, double dl_total_time, bool done)
872 char *p = bp->buffer;
873 wgint size = bp->initial_length + bp->count;
875 const char *size_grouped = with_thousand_seps (size);
876 int size_grouped_len = count_cols (size_grouped);
877 /* Difference between num cols and num bytes: */
878 int size_grouped_diff = strlen (size_grouped) - size_grouped_len;
879 int size_grouped_pad; /* Used to pad the field width for size_grouped. */
881 struct bar_progress_hist *hist = &bp->hist;
883 /* The progress bar should look like this:
884 xx% [=======> ] nn,nnn 12.34KB/s eta 36m 51s
886 Calculate the geometry. The idea is to assign as much room as
887 possible to the progress bar. The other idea is to never let
888 things "jitter", i.e. pad elements that vary in size so that
889 their variance does not affect the placement of other elements.
890 It would be especially bad for the progress bar to be resized
893 "xx% " or "100%" - percentage - 4 chars
894 "[]" - progress bar decorations - 2 chars
895 " nnn,nnn,nnn" - downloaded bytes - 12 chars or very rarely more
896 " 12.5KB/s" - download rate - 9 chars
897 " eta 36m 51s" - ETA - 14 chars
899 "=====>..." - progress bar - the rest
901 int dlbytes_size = 1 + MAX (size_grouped_len, 11);
902 int progress_size = bp->width - (4 + 2 + dlbytes_size + 8 + 14);
904 /* The difference between the number of bytes used,
905 and the number of columns used. */
906 int bytes_cols_diff = 0;
908 if (progress_size < 5)
912 if (bp->total_length > 0)
914 int percentage = 100.0 * size / bp->total_length;
915 assert (percentage <= 100);
917 if (percentage < 100)
918 sprintf (p, "%2d%% ", percentage);
924 APPEND_LITERAL (" ");
926 /* The progress bar: "[====> ]" or "[++==> ]". */
927 if (progress_size && bp->total_length > 0)
929 /* Size of the initial portion. */
930 int insz = (double)bp->initial_length / bp->total_length * progress_size;
932 /* Size of the downloaded portion. */
933 int dlsz = (double)size / bp->total_length * progress_size;
938 assert (dlsz <= progress_size);
939 assert (insz <= dlsz);
944 /* Print the initial portion of the download with '+' chars, the
945 rest with '=' and one '>'. */
946 for (i = 0; i < insz; i++)
951 for (i = 0; i < dlsz - 1; i++)
956 while (p - begin < progress_size)
960 else if (progress_size)
962 /* If we can't draw a real progress bar, then at least show
963 *something* to the user. */
964 int ind = bp->tick % (progress_size * 2 - 6);
967 /* Make the star move in two directions. */
968 if (ind < progress_size - 2)
971 pos = progress_size - (ind - progress_size + 5);
974 for (i = 0; i < progress_size; i++)
976 if (i == pos - 1) *p++ = '<';
977 else if (i == pos ) *p++ = '=';
978 else if (i == pos + 1) *p++ = '>';
988 sprintf (p, " %s", size_grouped);
990 /* Pad with spaces to 11 chars for the size_grouped field;
991 * couldn't use the field width specifier in sprintf, because
992 * it counts in bytes, not characters. */
993 for (size_grouped_pad = 11 - size_grouped_len;
994 size_grouped_pad > 0;
1000 /* " 12.52Kb/s or 12.52KB/s" */
1001 if (hist->total_time > 0 && hist->total_bytes)
1003 static const char *short_units[] = { "B/s", "KB/s", "MB/s", "GB/s" };
1004 static const char *short_units_bits[] = { "b/s", "Kb/s", "Mb/s", "Gb/s" };
1006 /* Calculate the download speed using the history ring and
1007 recent data that hasn't made it to the ring yet. */
1008 wgint dlquant = hist->total_bytes + bp->recent_bytes;
1009 double dltime = hist->total_time + (dl_total_time - bp->recent_start);
1010 double dlspeed = calc_rate (dlquant, dltime, &units);
1011 sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
1012 dlspeed, !opt.report_bps ? short_units[units] : short_units_bits[units]);
1016 APPEND_LITERAL (" --.-K/s");
1020 /* " eta ..m ..s"; wait for three seconds before displaying the ETA.
1021 That's because the ETA value needs a while to become
1023 if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
1027 /* Don't change the value of ETA more than approximately once
1028 per second; doing so would cause flashing without providing
1029 any value to the user. */
1030 if (bp->total_length != size
1031 && bp->last_eta_value != 0
1032 && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
1033 eta = bp->last_eta_value;
1036 /* Calculate ETA using the average download speed to predict
1037 the future speed. If you want to use a speed averaged
1038 over a more recent period, replace dl_total_time with
1039 hist->total_time and bp->count with hist->total_bytes.
1040 I found that doing that results in a very jerky and
1041 ultimately unreliable ETA. */
1042 wgint bytes_remaining = bp->total_length - size;
1043 double eta_ = dl_total_time * bytes_remaining / bp->count;
1044 if (eta_ >= INT_MAX - 1)
1046 eta = (int) (eta_ + 0.5);
1047 bp->last_eta_value = eta;
1048 bp->last_eta_time = dl_total_time;
1051 sprintf (p, get_eta(&bytes_cols_diff),
1052 eta_to_human_short (eta, false));
1055 else if (bp->total_length > 0)
1058 APPEND_LITERAL (" ");
1063 /* When the download is done, print the elapsed time. */
1067 /* Note to translators: this should not take up more room than
1068 available here. Abbreviate if necessary. */
1069 strcpy (p, _(" in "));
1070 nbytes = strlen (p);
1071 ncols = count_cols (p);
1072 bytes_cols_diff = nbytes - ncols;
1074 if (dl_total_time >= 10)
1075 strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
1077 sprintf (p, "%ss", print_decimal (dl_total_time));
1081 while (p - bp->buffer - bytes_cols_diff - size_grouped_diff < bp->width)
1086 /* Print the contents of the buffer as a one-line ASCII "image" so
1087 that it can be overwritten next time. */
1090 display_image (char *buf)
1092 bool old = log_set_save_context (false);
1093 logputs (LOG_VERBOSE, "\r");
1094 logputs (LOG_VERBOSE, buf);
1095 log_set_save_context (old);
1099 bar_set_params (const char *params)
1101 char *term = getenv ("TERM");
1104 && 0 == strcmp (params, "force"))
1105 current_impl_locked = 1;
1109 /* The progress bar doesn't make sense if the output is not a
1110 TTY -- when logging to file, it is better to review the
1112 || !isatty (fileno (stderr))
1114 /* Normally we don't depend on terminal type because the
1115 progress bar only uses ^M to move the cursor to the
1116 beginning of line, which works even on dumb terminals. But
1117 Jamie Zawinski reports that ^M and ^H tricks don't work in
1118 Emacs shell buffers, and only make a mess. */
1119 || (term && 0 == strcmp (term, "emacs"))
1121 && !current_impl_locked)
1123 /* We're not printing to a TTY, so revert to the fallback
1124 display. #### We're recursively calling
1125 set_progress_implementation here, which is slightly kludgy.
1126 It would be nicer if we provided that function a return value
1127 indicating a failure of some sort. */
1128 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1135 progress_handle_sigwinch (int sig)
1137 received_sigwinch = 1;
1138 signal (SIGWINCH, progress_handle_sigwinch);
1142 /* Provide a short human-readable rendition of the ETA. This is like
1143 secs_to_human_time in main.c, except the output doesn't include
1144 fractions (which would look silly in by nature imprecise ETA) and
1145 takes less room. If the time is measured in hours, hours and
1146 minutes (but not seconds) are shown; if measured in days, then days
1147 and hours are shown. This ensures brevity while still displaying
1148 as much as possible.
1150 If CONDENSED is true, the separator between minutes and seconds
1151 (and hours and minutes, etc.) is not included, shortening the
1152 display by one additional character. This is used for dot
1155 The display never occupies more than 7 characters of screen
1159 eta_to_human_short (int secs, bool condensed)
1161 static char buf[10]; /* 8 should be enough, but just in case */
1162 static int last = -1;
1163 const char *space = condensed ? "" : " ";
1165 /* Trivial optimization. create_image can call us every 200 msecs
1166 (see bar_update) for fast downloads, but ETA will only change
1167 once per 900 msecs. */
1173 sprintf (buf, "%ds", secs);
1174 else if (secs < 100 * 60)
1175 sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1176 else if (secs < 48 * 3600)
1177 sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1178 else if (secs < 100 * 86400)
1179 sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 24);
1181 /* even (2^31-1)/86400 doesn't overflow BUF. */
1182 sprintf (buf, "%dd", secs / 86400);