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) (const char *, wgint, wgint);
51 void (*update) (void *, wgint, double);
52 void (*draw) (void *);
53 void (*finish) (void *, double);
54 void (*set_params) (char *);
57 /* Necessary forward declarations. */
59 static void *dot_create (const char *, 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 (char *);
65 static void *bar_create (const char *, 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 (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 (const char *f_download, 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 (f_download, 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 _GL_UNUSED)
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 (const char *f_download _GL_UNUSED, 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_PROGRESS, _("\n%*s[ skipping %sK ]"),
246 2 + skipped_k_len, "",
247 number_to_static_string (skipped_k));
250 logprintf (LOG_PROGRESS, "\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_PROGRESS, " ");
256 logputs (LOG_PROGRESS, ",");
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_PROGRESS, "%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_PROGRESS, " %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_PROGRESS, " %s",
332 eta_to_human_short ((int) (eta + 0.5), true));
337 /* When done, print the total download time */
339 logprintf (LOG_PROGRESS, "=%s",
340 eta_to_human_short ((int) (dltime + 0.5), true));
342 logprintf (LOG_PROGRESS, "=%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_PROGRESS, "\n%6sK",
369 number_to_static_string (dp->rows * ROW_BYTES / 1024));
371 if (dp->dots % opt.dot_spacing == 0)
372 logputs (LOG_PROGRESS, " ");
373 logputs (LOG_PROGRESS, ".");
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_PROGRESS, "\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_PROGRESS, " ");
406 logputs (LOG_PROGRESS, " ");
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 (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 const char *f_download; /* Filename of the downloaded file */
511 wgint initial_length; /* how many bytes have been downloaded
513 wgint total_length; /* expected total byte count when the
515 wgint count; /* bytes downloaded so far */
517 double last_screen_update; /* time of the last screen update,
518 measured since the beginning of
521 double dltime; /* download time so far */
522 int width; /* screen width we're using at the
523 time the progress gauge was
524 created. this is different from
525 the screen_width global variable in
526 that the latter can be changed by a
528 char *buffer; /* buffer where the bar "image" is
530 int tick; /* counter used for drawing the
531 progress bar where the total size
534 /* The following variables (kept in a struct for namespace reasons)
535 keep track of recent download speeds. See bar_update() for
537 struct bar_progress_hist {
539 double times[DLSPEED_HISTORY_SIZE];
540 wgint bytes[DLSPEED_HISTORY_SIZE];
542 /* The sum of times and bytes respectively, maintained for
548 double recent_start; /* timestamp of beginning of current
550 wgint recent_bytes; /* bytes downloaded so far. */
552 bool stalled; /* set when no data arrives for longer
553 than STALL_START_TIME, then reset
554 when new data arrives. */
556 /* create_image() uses these to make sure that ETA information
558 double last_eta_time; /* time of the last update to download
559 speed and ETA, measured since the
560 beginning of download. */
564 static void create_image (struct bar_progress *, double, bool);
565 static void display_image (char *);
568 bar_create (const char *f_download, wgint initial, wgint total)
570 struct bar_progress *bp = xnew0 (struct bar_progress);
572 /* In theory, our callers should take care of this pathological
573 case, but it can sometimes happen. */
577 bp->initial_length = initial;
578 bp->total_length = total;
579 bp->f_download = f_download;
581 /* Initialize screen_width if this hasn't been done or if it might
582 have changed, as indicated by receiving SIGWINCH. */
583 if (!screen_width || received_sigwinch)
585 screen_width = determine_screen_width ();
587 screen_width = DEFAULT_SCREEN_WIDTH;
588 else if (screen_width < MINIMUM_SCREEN_WIDTH)
589 screen_width = MINIMUM_SCREEN_WIDTH;
590 received_sigwinch = 0;
593 /* - 1 because we don't want to use the last screen column. */
594 bp->width = screen_width - 1;
595 /* + enough space for the terminating zero, and hopefully enough room
596 * for multibyte characters. */
597 bp->buffer = xmalloc (bp->width + 100);
599 logputs (LOG_VERBOSE, "\n");
601 create_image (bp, 0, false);
602 display_image (bp->buffer);
607 static void update_speed_ring (struct bar_progress *, wgint, double);
610 bar_update (void *progress, wgint howmuch, double dltime)
612 struct bar_progress *bp = progress;
615 bp->count += howmuch;
616 if (bp->total_length > 0
617 && bp->count + bp->initial_length > bp->total_length)
618 /* We could be downloading more than total_length, e.g. when the
619 server sends an incorrect Content-Length header. In that case,
620 adjust bp->total_length to the new reality, so that the code in
621 create_image() that depends on total size being smaller or
622 equal to the expected size doesn't abort. */
623 bp->total_length = bp->initial_length + bp->count;
625 update_speed_ring (bp, howmuch, dltime);
629 bar_draw (void *progress)
631 bool force_screen_update = false;
632 struct bar_progress *bp = progress;
634 /* If SIGWINCH (the window size change signal) been received,
635 determine the new screen size and update the screen. */
636 if (received_sigwinch)
638 int old_width = screen_width;
639 screen_width = determine_screen_width ();
641 screen_width = DEFAULT_SCREEN_WIDTH;
642 else if (screen_width < MINIMUM_SCREEN_WIDTH)
643 screen_width = MINIMUM_SCREEN_WIDTH;
644 if (screen_width != old_width)
646 bp->width = screen_width - 1;
647 bp->buffer = xrealloc (bp->buffer, bp->width + 100);
648 force_screen_update = true;
650 received_sigwinch = 0;
653 if (bp->dltime - bp->last_screen_update < REFRESH_INTERVAL && !force_screen_update)
654 /* Don't update more often than five times per second. */
657 create_image (bp, bp->dltime, false);
658 display_image (bp->buffer);
659 bp->last_screen_update = bp->dltime;
663 bar_finish (void *progress, double dltime)
665 struct bar_progress *bp = progress;
667 if (bp->total_length > 0
668 && bp->count + bp->initial_length > bp->total_length)
669 /* See bar_update() for explanation. */
670 bp->total_length = bp->initial_length + bp->count;
672 create_image (bp, dltime, true);
673 display_image (bp->buffer);
675 logputs (LOG_VERBOSE, "\n");
676 logputs (LOG_PROGRESS, "\n");
682 /* This code attempts to maintain the notion of a "current" download
683 speed, over the course of no less than 3s. (Shorter intervals
684 produce very erratic results.)
686 To do so, it samples the speed in 150ms intervals and stores the
687 recorded samples in a FIFO history ring. The ring stores no more
688 than 20 intervals, hence the history covers the period of at least
689 three seconds and at most 20 reads into the past. This method
690 should produce reasonable results for downloads ranging from very
693 The idea is that for fast downloads, we get the speed over exactly
694 the last three seconds. For slow downloads (where a network read
695 takes more than 150ms to complete), we get the speed over a larger
696 time period, as large as it takes to complete thirty reads. This
697 is good because slow downloads tend to fluctuate more and a
698 3-second average would be too erratic. */
701 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
703 struct bar_progress_hist *hist = &bp->hist;
704 double recent_age = dltime - bp->recent_start;
706 /* Update the download count. */
707 bp->recent_bytes += howmuch;
709 /* For very small time intervals, we return after having updated the
710 "recent" download count. When its age reaches or exceeds minimum
711 sample time, it will be recorded in the history ring. */
712 if (recent_age < DLSPEED_SAMPLE_MIN)
717 /* If we're not downloading anything, we might be stalling,
718 i.e. not downloading anything for an extended period of time.
719 Since 0-reads do not enter the history ring, recent_age
720 effectively measures the time since last read. */
721 if (recent_age >= STALL_START_TIME)
723 /* If we're stalling, reset the ring contents because it's
724 stale and because it will make bar_update stop printing
725 the (bogus) current bandwidth. */
728 bp->recent_bytes = 0;
733 /* We now have a non-zero amount of to store to the speed ring. */
735 /* If the stall status was acquired, reset it. */
739 /* "recent_age" includes the entired stalled period, which
740 could be very long. Don't update the speed ring with that
741 value because the current bandwidth would start too small.
742 Start with an arbitrary (but more reasonable) time value and
747 /* Store "recent" bytes and download time to history ring at the
750 /* To correctly maintain the totals, first invalidate existing data
751 (least recent in time) at this position. */
752 hist->total_time -= hist->times[hist->pos];
753 hist->total_bytes -= hist->bytes[hist->pos];
755 /* Now store the new data and update the totals. */
756 hist->times[hist->pos] = recent_age;
757 hist->bytes[hist->pos] = bp->recent_bytes;
758 hist->total_time += recent_age;
759 hist->total_bytes += bp->recent_bytes;
761 /* Start a new "recent" period. */
762 bp->recent_start = dltime;
763 bp->recent_bytes = 0;
765 /* Advance the current ring position. */
766 if (++hist->pos == DLSPEED_HISTORY_SIZE)
770 /* Sledgehammer check to verify that the totals are accurate. */
773 double sumt = 0, sumb = 0;
774 for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
776 sumt += hist->times[i];
777 sumb += hist->bytes[i];
779 assert (sumb == hist->total_bytes);
780 /* We can't use assert(sumt==hist->total_time) because some
781 precision is lost by adding and subtracting floating-point
782 numbers. But during a download this precision should not be
783 detectable, i.e. no larger than 1ns. */
784 double diff = sumt - hist->total_time;
785 if (diff < 0) diff = -diff;
786 assert (diff < 1e-9);
791 #if USE_NLS_PROGRESS_BAR
793 count_cols (const char *mbs)
797 int remaining = strlen(mbs);
803 bytes = mbtowc (&wc, mbs, remaining);
804 assert (bytes != 0); /* Only happens when *mbs == '\0' */
807 /* Invalid sequence. We'll just have to fudge it. */
808 return cols + remaining;
812 wccols = wcwidth(wc);
813 cols += (wccols == -1? 1 : wccols);
818 # define count_cols(mbs) ((int)(strlen(mbs)))
824 /* TRANSLATORS: "ETA" is English-centric, but this must
825 be short, ideally 3 chars. Abbreviate if necessary. */
826 static const char eta_str[] = N_(" eta %s");
827 static const char *eta_trans;
828 static int bytes_cols_diff;
829 if (eta_trans == NULL)
834 #if USE_NLS_PROGRESS_BAR
835 eta_trans = _(eta_str);
840 /* Determine the number of bytes used in the translated string,
841 * versus the number of columns used. This is to figure out how
842 * many spaces to add at the end to pad to the full line width.
844 * We'll store the difference between the number of bytes and
845 * number of columns, so that removing this from the string length
846 * will reveal the total number of columns in the progress bar. */
847 nbytes = strlen (eta_trans);
848 ncols = count_cols (eta_trans);
849 bytes_cols_diff = nbytes - ncols;
853 *bcd = bytes_cols_diff;
858 #define APPEND_LITERAL(s) do { \
859 memcpy (p, s, sizeof (s) - 1); \
860 p += sizeof (s) - 1; \
863 /* Use move_to_end (s) to get S to point the end of the string (the
864 terminating \0). This is faster than s+=strlen(s), but some people
865 are confused when they see strchr (s, '\0') in the code. */
866 #define move_to_end(s) s = strchr (s, '\0');
869 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
872 # define MIN(a, b) ((a) <= (b) ? (a) : (b))
876 create_image (struct bar_progress *bp, double dl_total_time, bool done)
878 const int MAX_FILENAME_LEN = bp->width / 4;
879 char *p = bp->buffer;
880 wgint size = bp->initial_length + bp->count;
882 const char *size_grouped = with_thousand_seps (size);
883 int size_grouped_len = count_cols (size_grouped);
884 /* Difference between num cols and num bytes: */
885 int size_grouped_diff = strlen (size_grouped) - size_grouped_len;
886 int size_grouped_pad; /* Used to pad the field width for size_grouped. */
888 struct bar_progress_hist *hist = &bp->hist;
889 int orig_filename_len = strlen (bp->f_download);
891 /* The progress bar should look like this:
892 file xx% [=======> ] nnn.nnK 12.34KB/s eta 36m 51s
894 Calculate the geometry. The idea is to assign as much room as
895 possible to the progress bar. The other idea is to never let
896 things "jitter", i.e. pad elements that vary in size so that
897 their variance does not affect the placement of other elements.
898 It would be especially bad for the progress bar to be resized
901 "file " - Downloaded filename - MAX_FILENAME_LEN chars + 1
902 "xx% " or "100%" - percentage - 4 chars
903 "[]" - progress bar decorations - 2 chars
904 " nnn.nnK" - downloaded bytes - 7 chars + 1
905 " 12.5KB/s" - download rate - 8 chars + 1
906 " eta 36m 51s" - ETA - 14 chars
908 "=====>..." - progress bar - the rest
911 #define PROGRESS_FILENAME_LEN MAX_FILENAME_LEN + 1
912 #define PROGRESS_PERCENT_LEN 4
913 #define PROGRESS_DECORAT_LEN 2
914 #define PROGRESS_FILESIZE_LEN 7 + 1
915 #define PROGRESS_DWNLOAD_RATE 8 + 1
916 #define PROGRESS_ETA_LEN 14
918 int progress_size = bp->width - (PROGRESS_FILENAME_LEN + PROGRESS_PERCENT_LEN +
919 PROGRESS_DECORAT_LEN + PROGRESS_FILESIZE_LEN +
920 PROGRESS_DWNLOAD_RATE + PROGRESS_ETA_LEN);
922 /* The difference between the number of bytes used,
923 and the number of columns used. */
924 int bytes_cols_diff = 0;
926 if (progress_size < 5)
929 if (orig_filename_len <= MAX_FILENAME_LEN)
931 int padding = MAX_FILENAME_LEN - orig_filename_len;
932 sprintf (p, "%s ", bp->f_download);
933 p += orig_filename_len + 1;
934 for (;padding;padding--)
941 if (((orig_filename_len > MAX_FILENAME_LEN) && !opt.noscroll) && !done)
942 offset = ((int) bp->tick) % (orig_filename_len - MAX_FILENAME_LEN);
945 memcpy (p, bp->f_download + offset, MAX_FILENAME_LEN);
946 p += MAX_FILENAME_LEN;
951 if (bp->total_length > 0)
953 int percentage = 100.0 * size / bp->total_length;
954 assert (percentage <= 100);
956 if (percentage < 100)
957 sprintf (p, "%2d%% ", percentage);
963 APPEND_LITERAL (" ");
965 /* The progress bar: "[====> ]" or "[++==> ]". */
966 if (progress_size && bp->total_length > 0)
968 /* Size of the initial portion. */
969 int insz = (double)bp->initial_length / bp->total_length * progress_size;
971 /* Size of the downloaded portion. */
972 int dlsz = (double)size / bp->total_length * progress_size;
977 assert (dlsz <= progress_size);
978 assert (insz <= dlsz);
983 /* Print the initial portion of the download with '+' chars, the
984 rest with '=' and one '>'. */
985 for (i = 0; i < insz; i++)
990 for (i = 0; i < dlsz - 1; i++)
995 while (p - begin < progress_size)
999 else if (progress_size)
1001 /* If we can't draw a real progress bar, then at least show
1002 *something* to the user. */
1003 int ind = bp->tick % (progress_size * 2 - 6);
1006 /* Make the star move in two directions. */
1007 if (ind < progress_size - 2)
1010 pos = progress_size - (ind - progress_size + 5);
1013 for (i = 0; i < progress_size; i++)
1015 if (i == pos - 1) *p++ = '<';
1016 else if (i == pos ) *p++ = '=';
1017 else if (i == pos + 1) *p++ = '>';
1027 const char * down_size = human_readable (size, 1000, 2);
1028 int cols_diff = 7 - count_cols (down_size);
1029 while (cols_diff > 0)
1034 sprintf (p, " %s", down_size);
1036 /* Pad with spaces to 7 chars for the size_grouped field;
1037 * couldn't use the field width specifier in sprintf, because
1038 * it counts in bytes, not characters. */
1039 for (size_grouped_pad = PROGRESS_FILESIZE_LEN - 7;
1040 size_grouped_pad > 0;
1046 /* " 12.52Kb/s or 12.52KB/s" */
1047 if (hist->total_time > 0 && hist->total_bytes)
1049 static const char *short_units[] = { " B/s", "KB/s", "MB/s", "GB/s" };
1050 static const char *short_units_bits[] = { " b/s", "Kb/s", "Mb/s", "Gb/s" };
1052 /* Calculate the download speed using the history ring and
1053 recent data that hasn't made it to the ring yet. */
1054 wgint dlquant = hist->total_bytes + bp->recent_bytes;
1055 double dltime = hist->total_time + (dl_total_time - bp->recent_start);
1056 double dlspeed = calc_rate (dlquant, dltime, &units);
1057 sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
1058 dlspeed, !opt.report_bps ? short_units[units] : short_units_bits[units]);
1062 APPEND_LITERAL (" --.-KB/s");
1066 /* " eta ..m ..s"; wait for three seconds before displaying the ETA.
1067 That's because the ETA value needs a while to become
1069 if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
1073 /* Don't change the value of ETA more than approximately once
1074 per second; doing so would cause flashing without providing
1075 any value to the user. */
1076 if (bp->total_length != size
1077 && bp->last_eta_value != 0
1078 && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
1079 eta = bp->last_eta_value;
1082 /* Calculate ETA using the average download speed to predict
1083 the future speed. If you want to use a speed averaged
1084 over a more recent period, replace dl_total_time with
1085 hist->total_time and bp->count with hist->total_bytes.
1086 I found that doing that results in a very jerky and
1087 ultimately unreliable ETA. */
1088 wgint bytes_remaining = bp->total_length - size;
1089 double eta_ = dl_total_time * bytes_remaining / bp->count;
1090 if (eta_ >= INT_MAX - 1)
1092 eta = (int) (eta_ + 0.5);
1093 bp->last_eta_value = eta;
1094 bp->last_eta_time = dl_total_time;
1097 sprintf (p, get_eta(&bytes_cols_diff),
1098 eta_to_human_short (eta, false));
1101 else if (bp->total_length > 0)
1104 APPEND_LITERAL (" ");
1109 /* When the download is done, print the elapsed time. */
1113 /* Note to translators: this should not take up more room than
1114 available here. Abbreviate if necessary. */
1115 strcpy (p, _(" in "));
1116 nbytes = strlen (p);
1117 ncols = count_cols (p);
1118 bytes_cols_diff = nbytes - ncols;
1120 if (dl_total_time >= 10)
1121 strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
1123 sprintf (p, "%ss", print_decimal (dl_total_time));
1127 while (p - bp->buffer - bytes_cols_diff - size_grouped_diff < bp->width)
1132 /* Print the contents of the buffer as a one-line ASCII "image" so
1133 that it can be overwritten next time. */
1136 display_image (char *buf)
1138 bool old = log_set_save_context (false);
1139 logputs (LOG_PROGRESS, "\r");
1140 logputs (LOG_PROGRESS, buf);
1141 log_set_save_context (old);
1145 bar_set_params (char *params)
1147 char *term = getenv ("TERM");
1151 char *param = strtok (params, ":");
1154 if (0 == strcmp (param, "force"))
1155 current_impl_locked = 1;
1156 else if (0 == strcmp (param, "noscroll"))
1157 opt.noscroll = true;
1158 } while ((param = strtok (NULL, ":")) != NULL);
1163 /* The progress bar doesn't make sense if the output is not a
1164 TTY -- when logging to file, it is better to review the
1166 || !isatty (fileno (stderr))
1168 /* Normally we don't depend on terminal type because the
1169 progress bar only uses ^M to move the cursor to the
1170 beginning of line, which works even on dumb terminals. But
1171 Jamie Zawinski reports that ^M and ^H tricks don't work in
1172 Emacs shell buffers, and only make a mess. */
1173 || (term && 0 == strcmp (term, "emacs"))
1175 && !current_impl_locked)
1177 /* We're not printing to a TTY, so revert to the fallback
1178 display. #### We're recursively calling
1179 set_progress_implementation here, which is slightly kludgy.
1180 It would be nicer if we provided that function a return value
1181 indicating a failure of some sort. */
1182 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1189 progress_handle_sigwinch (int sig _GL_UNUSED)
1191 received_sigwinch = 1;
1192 signal (SIGWINCH, progress_handle_sigwinch);
1196 /* Provide a short human-readable rendition of the ETA. This is like
1197 secs_to_human_time in main.c, except the output doesn't include
1198 fractions (which would look silly in by nature imprecise ETA) and
1199 takes less room. If the time is measured in hours, hours and
1200 minutes (but not seconds) are shown; if measured in days, then days
1201 and hours are shown. This ensures brevity while still displaying
1202 as much as possible.
1204 If CONDENSED is true, the separator between minutes and seconds
1205 (and hours and minutes, etc.) is not included, shortening the
1206 display by one additional character. This is used for dot
1209 The display never occupies more than 7 characters of screen
1213 eta_to_human_short (int secs, bool condensed)
1215 static char buf[10]; /* 8 should be enough, but just in case */
1216 static int last = -1;
1217 const char *space = condensed ? "" : " ";
1219 /* Trivial optimization. create_image can call us every 200 msecs
1220 (see bar_update) for fast downloads, but ETA will only change
1221 once per 900 msecs. */
1227 sprintf (buf, "%ds", secs);
1228 else if (secs < 100 * 60)
1229 sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1230 else if (secs < 48 * 3600)
1231 sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1232 else if (secs < 100 * 86400)
1233 sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 24);
1235 /* even (2^31-1)/86400 doesn't overflow BUF. */
1236 sprintf (buf, "%dd", secs / 86400);