2 Copyright (C) 2001-2006 Free Software Foundation, Inc.
4 This file is part of GNU Wget.
6 GNU Wget is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 GNU Wget is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with Wget. If not, see <http://www.gnu.org/licenses/>.
19 In addition, as a special exception, the Free Software Foundation
20 gives permission to link the code of its release of Wget with the
21 OpenSSL project's "OpenSSL" library (or with modified versions of it
22 that use the same license as the "OpenSSL" library), and distribute
23 the linked executables. You must obey the GNU General Public License
24 in all respects for all of the code used other than "OpenSSL". If you
25 modify this file, you may extend this exception to your version of the
26 file, but you are not obligated to do so. If you do not wish to do
27 so, delete this exception statement from your version. */
45 struct progress_implementation {
48 void *(*create) (wgint, wgint);
49 void (*update) (void *, wgint, double);
50 void (*finish) (void *, double);
51 void (*set_params) (const char *);
54 /* Necessary forward declarations. */
56 static void *dot_create (wgint, wgint);
57 static void dot_update (void *, wgint, double);
58 static void dot_finish (void *, double);
59 static void dot_set_params (const char *);
61 static void *bar_create (wgint, wgint);
62 static void bar_update (void *, wgint, double);
63 static void bar_finish (void *, double);
64 static void bar_set_params (const char *);
66 static struct progress_implementation implementations[] = {
67 { "dot", 0, dot_create, dot_update, dot_finish, dot_set_params },
68 { "bar", 1, bar_create, bar_update, bar_finish, bar_set_params }
70 static struct progress_implementation *current_impl;
71 static int current_impl_locked;
73 /* Progress implementation used by default. Can be overriden in
74 wgetrc or by the fallback one. */
76 #define DEFAULT_PROGRESS_IMPLEMENTATION "bar"
78 /* Fallback progress implementation should be something that works
79 under all display types. If you put something other than "dot"
80 here, remember that bar_set_params tries to switch to this if we're
81 not running on a TTY. So changing this to "bar" could cause
84 #define FALLBACK_PROGRESS_IMPLEMENTATION "dot"
86 /* Return true if NAME names a valid progress bar implementation. The
87 characters after the first : will be ignored. */
90 valid_progress_implementation_p (const char *name)
93 struct progress_implementation *pi = implementations;
94 char *colon = strchr (name, ':');
95 int namelen = colon ? colon - name : strlen (name);
97 for (i = 0; i < countof (implementations); i++, pi++)
98 if (!strncmp (pi->name, name, namelen))
103 /* Set the progress implementation to NAME. */
106 set_progress_implementation (const char *name)
109 struct progress_implementation *pi = implementations;
113 name = DEFAULT_PROGRESS_IMPLEMENTATION;
115 colon = strchr (name, ':');
116 namelen = colon ? colon - name : strlen (name);
118 for (i = 0; i < countof (implementations); i++, pi++)
119 if (!strncmp (pi->name, name, namelen))
122 current_impl_locked = 0;
125 /* We call pi->set_params even if colon is NULL because we
126 want to give the implementation a chance to set up some
127 things it needs to run. */
131 pi->set_params (colon);
137 static int output_redirected;
140 progress_schedule_redirect (void)
142 output_redirected = 1;
145 /* Create a progress gauge. INITIAL is the number of bytes the
146 download starts from (zero if the download starts from scratch).
147 TOTAL is the expected total number of bytes in this download. If
148 TOTAL is zero, it means that the download size is not known in
152 progress_create (wgint initial, wgint total)
154 /* Check if the log status has changed under our feet. */
155 if (output_redirected)
157 if (!current_impl_locked)
158 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
159 output_redirected = 0;
162 return current_impl->create (initial, total);
165 /* Return true if the progress gauge is "interactive", i.e. if it can
166 profit from being called regularly even in absence of data. The
167 progress bar is interactive because it regularly updates the ETA
168 and current update. */
171 progress_interactive_p (void *progress)
173 return current_impl->interactive;
176 /* Inform the progress gauge of newly received bytes. DLTIME is the
177 time since the beginning of the download. */
180 progress_update (void *progress, wgint howmuch, double dltime)
182 current_impl->update (progress, howmuch, dltime);
185 /* Tell the progress gauge to clean up. Calling this will free the
186 PROGRESS object, the further use of which is not allowed. */
189 progress_finish (void *progress, double dltime)
191 current_impl->finish (progress, dltime);
196 struct dot_progress {
197 wgint initial_length; /* how many bytes have been downloaded
199 wgint total_length; /* expected total byte count when the
202 int accumulated; /* number of bytes accumulated after
203 the last printed dot */
205 int rows; /* number of rows printed so far */
206 int dots; /* number of dots printed in this row */
208 double last_timer_value;
211 /* Dot-progress backend for progress_create. */
214 dot_create (wgint initial, wgint total)
216 struct dot_progress *dp = xnew0 (struct dot_progress);
217 dp->initial_length = initial;
218 dp->total_length = total;
220 if (dp->initial_length)
222 int dot_bytes = opt.dot_bytes;
223 const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
225 int remainder = dp->initial_length % ROW_BYTES;
226 wgint skipped = dp->initial_length - remainder;
230 wgint skipped_k = skipped / 1024; /* skipped amount in K */
231 int skipped_k_len = numdigit (skipped_k);
232 if (skipped_k_len < 6)
235 /* Align the [ skipping ... ] line with the dots. To do
236 that, insert the number of spaces equal to the number of
237 digits in the skipped amount in K. */
238 logprintf (LOG_VERBOSE, _("\n%*s[ skipping %sK ]"),
239 2 + skipped_k_len, "",
240 number_to_static_string (skipped_k));
243 logprintf (LOG_VERBOSE, "\n%6sK",
244 number_to_static_string (skipped / 1024));
245 for (; remainder >= dot_bytes; remainder -= dot_bytes)
247 if (dp->dots % opt.dot_spacing == 0)
248 logputs (LOG_VERBOSE, " ");
249 logputs (LOG_VERBOSE, ",");
252 assert (dp->dots < opt.dots_in_line);
254 dp->accumulated = remainder;
255 dp->rows = skipped / ROW_BYTES;
261 static const char *eta_to_human_short (int, bool);
263 /* Prints the stats (percentage of completion, speed, ETA) for current
264 row. DLTIME is the time spent downloading the data in current
267 #### This function is somewhat uglified by the fact that current
268 row and last row have somewhat different stats requirements. It
269 might be worthwhile to split it to two different functions. */
272 print_row_stats (struct dot_progress *dp, double dltime, bool last)
274 const wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
276 /* bytes_displayed is the number of bytes indicated to the user by
277 dots printed so far, includes the initially "skipped" amount */
278 wgint bytes_displayed = dp->rows * ROW_BYTES + dp->dots * opt.dot_bytes;
281 /* For last row also count bytes accumulated after last dot */
282 bytes_displayed += dp->accumulated;
284 if (dp->total_length)
286 /* Round to floor value to provide gauge how much data *has*
287 been retrieved. 12.8% will round to 12% because the 13% mark
288 has not yet been reached. 100% is only shown when done. */
289 int percentage = 100.0 * bytes_displayed / dp->total_length;
290 logprintf (LOG_VERBOSE, "%3d%%", percentage);
294 static char names[] = {' ', 'K', 'M', 'G'};
297 wgint bytes_this_row;
299 bytes_this_row = ROW_BYTES;
301 /* For last row also include bytes accumulated after last dot. */
302 bytes_this_row = dp->dots * opt.dot_bytes + dp->accumulated;
303 /* Don't count the portion of the row belonging to initial_length */
304 if (dp->rows == dp->initial_length / ROW_BYTES)
305 bytes_this_row -= dp->initial_length % ROW_BYTES;
306 rate = calc_rate (bytes_this_row, dltime - dp->last_timer_value, &units);
307 logprintf (LOG_VERBOSE, " %4.*f%c",
308 rate >= 99.95 ? 0 : rate >= 9.995 ? 1 : 2,
310 dp->last_timer_value = dltime;
315 /* Display ETA based on average speed. Inspired by Vladi
316 Belperchinov-Shabanski's "wget-new-percentage" patch. */
317 if (dp->total_length)
319 wgint bytes_remaining = dp->total_length - bytes_displayed;
320 /* The quantity downloaded in this download run. */
321 wgint bytes_sofar = bytes_displayed - dp->initial_length;
322 double eta = dltime * bytes_remaining / bytes_sofar;
323 if (eta < INT_MAX - 1)
324 logprintf (LOG_VERBOSE, " %s",
325 eta_to_human_short ((int) (eta + 0.5), true));
330 /* When done, print the total download time */
332 logprintf (LOG_VERBOSE, "=%s",
333 eta_to_human_short ((int) (dltime + 0.5), true));
335 logprintf (LOG_VERBOSE, "=%ss", print_decimal (dltime));
339 /* Dot-progress backend for progress_update. */
342 dot_update (void *progress, wgint howmuch, double dltime)
344 struct dot_progress *dp = progress;
345 int dot_bytes = opt.dot_bytes;
346 wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
348 log_set_flush (false);
350 dp->accumulated += howmuch;
351 for (; dp->accumulated >= dot_bytes; dp->accumulated -= dot_bytes)
354 logprintf (LOG_VERBOSE, "\n%6sK",
355 number_to_static_string (dp->rows * ROW_BYTES / 1024));
357 if (dp->dots % opt.dot_spacing == 0)
358 logputs (LOG_VERBOSE, " ");
359 logputs (LOG_VERBOSE, ".");
362 if (dp->dots >= opt.dots_in_line)
367 print_row_stats (dp, dltime, false);
371 log_set_flush (true);
374 /* Dot-progress backend for progress_finish. */
377 dot_finish (void *progress, double dltime)
379 struct dot_progress *dp = progress;
380 wgint ROW_BYTES = opt.dot_bytes * opt.dots_in_line;
383 log_set_flush (false);
386 logprintf (LOG_VERBOSE, "\n%6sK",
387 number_to_static_string (dp->rows * ROW_BYTES / 1024));
388 for (i = dp->dots; i < opt.dots_in_line; i++)
390 if (i % opt.dot_spacing == 0)
391 logputs (LOG_VERBOSE, " ");
392 logputs (LOG_VERBOSE, " ");
395 print_row_stats (dp, dltime, true);
396 logputs (LOG_VERBOSE, "\n\n");
397 log_set_flush (false);
402 /* This function interprets the progress "parameters". For example,
403 if Wget is invoked with --progress=dot:mega, it will set the
404 "dot-style" to "mega". Valid styles are default, binary, mega, and
408 dot_set_params (const char *params)
410 if (!params || !*params)
411 params = opt.dot_style;
416 /* We use this to set the retrieval style. */
417 if (!strcasecmp (params, "default"))
419 /* Default style: 1K dots, 10 dots in a cluster, 50 dots in a
421 opt.dot_bytes = 1024;
422 opt.dot_spacing = 10;
423 opt.dots_in_line = 50;
425 else if (!strcasecmp (params, "binary"))
427 /* "Binary" retrieval: 8K dots, 16 dots in a cluster, 48 dots
429 opt.dot_bytes = 8192;
430 opt.dot_spacing = 16;
431 opt.dots_in_line = 48;
433 else if (!strcasecmp (params, "mega"))
435 /* "Mega" retrieval, for retrieving very long files; each dot is
436 64K, 8 dots in a cluster, 6 clusters (3M) in a line. */
437 opt.dot_bytes = 65536L;
439 opt.dots_in_line = 48;
441 else if (!strcasecmp (params, "giga"))
443 /* "Giga" retrieval, for retrieving very very *very* long files;
444 each dot is 1M, 8 dots in a cluster, 4 clusters (32M) in a
446 opt.dot_bytes = (1L << 20);
448 opt.dots_in_line = 32;
452 _("Invalid dot style specification `%s'; leaving unchanged.\n"),
456 /* "Thermometer" (bar) progress. */
458 /* Assumed screen width if we can't find the real value. */
459 #define DEFAULT_SCREEN_WIDTH 80
461 /* Minimum screen width we'll try to work with. If this is too small,
462 create_image will overflow the buffer. */
463 #define MINIMUM_SCREEN_WIDTH 45
465 /* The last known screen width. This can be updated by the code that
466 detects that SIGWINCH was received (but it's never updated from the
468 static int screen_width;
470 /* A flag that, when set, means SIGWINCH was received. */
471 static volatile sig_atomic_t received_sigwinch;
473 /* Size of the download speed history ring. */
474 #define DLSPEED_HISTORY_SIZE 20
476 /* The minimum time length of a history sample. By default, each
477 sample is at least 150ms long, which means that, over the course of
478 20 samples, "current" download speed spans at least 3s into the
480 #define DLSPEED_SAMPLE_MIN 0.15
482 /* The time after which the download starts to be considered
483 "stalled", i.e. the current bandwidth is not printed and the recent
484 download speeds are scratched. */
485 #define STALL_START_TIME 5
487 /* Time between screen refreshes will not be shorter than this, so
488 that Wget doesn't swamp the TTY with output. */
489 #define REFRESH_INTERVAL 0.2
491 /* Don't refresh the ETA too often to avoid jerkiness in predictions.
492 This allows ETA to change approximately once per second. */
493 #define ETA_REFRESH_INTERVAL 0.99
495 struct bar_progress {
496 wgint initial_length; /* how many bytes have been downloaded
498 wgint total_length; /* expected total byte count when the
500 wgint count; /* bytes downloaded so far */
502 double last_screen_update; /* time of the last screen update,
503 measured since the beginning of
506 int width; /* screen width we're using at the
507 time the progress gauge was
508 created. this is different from
509 the screen_width global variable in
510 that the latter can be changed by a
512 char *buffer; /* buffer where the bar "image" is
514 int tick; /* counter used for drawing the
515 progress bar where the total size
518 /* The following variables (kept in a struct for namespace reasons)
519 keep track of recent download speeds. See bar_update() for
521 struct bar_progress_hist {
523 double times[DLSPEED_HISTORY_SIZE];
524 wgint bytes[DLSPEED_HISTORY_SIZE];
526 /* The sum of times and bytes respectively, maintained for
532 double recent_start; /* timestamp of beginning of current
534 wgint recent_bytes; /* bytes downloaded so far. */
536 bool stalled; /* set when no data arrives for longer
537 than STALL_START_TIME, then reset
538 when new data arrives. */
540 /* create_image() uses these to make sure that ETA information
542 double last_eta_time; /* time of the last update to download
543 speed and ETA, measured since the
544 beginning of download. */
548 static void create_image (struct bar_progress *, double, bool);
549 static void display_image (char *);
552 bar_create (wgint initial, wgint total)
554 struct bar_progress *bp = xnew0 (struct bar_progress);
556 /* In theory, our callers should take care of this pathological
557 case, but it can sometimes happen. */
561 bp->initial_length = initial;
562 bp->total_length = total;
564 /* Initialize screen_width if this hasn't been done or if it might
565 have changed, as indicated by receiving SIGWINCH. */
566 if (!screen_width || received_sigwinch)
568 screen_width = determine_screen_width ();
570 screen_width = DEFAULT_SCREEN_WIDTH;
571 else if (screen_width < MINIMUM_SCREEN_WIDTH)
572 screen_width = MINIMUM_SCREEN_WIDTH;
573 received_sigwinch = 0;
576 /* - 1 because we don't want to use the last screen column. */
577 bp->width = screen_width - 1;
578 /* + 1 for the terminating zero. */
579 bp->buffer = xmalloc (bp->width + 1);
581 logputs (LOG_VERBOSE, "\n");
583 create_image (bp, 0, false);
584 display_image (bp->buffer);
589 static void update_speed_ring (struct bar_progress *, wgint, double);
592 bar_update (void *progress, wgint howmuch, double dltime)
594 struct bar_progress *bp = progress;
595 bool force_screen_update = false;
597 bp->count += howmuch;
598 if (bp->total_length > 0
599 && bp->count + bp->initial_length > bp->total_length)
600 /* We could be downloading more than total_length, e.g. when the
601 server sends an incorrect Content-Length header. In that case,
602 adjust bp->total_length to the new reality, so that the code in
603 create_image() that depends on total size being smaller or
604 equal to the expected size doesn't abort. */
605 bp->total_length = bp->initial_length + bp->count;
607 update_speed_ring (bp, howmuch, dltime);
609 /* If SIGWINCH (the window size change signal) been received,
610 determine the new screen size and update the screen. */
611 if (received_sigwinch)
613 int old_width = screen_width;
614 screen_width = determine_screen_width ();
616 screen_width = DEFAULT_SCREEN_WIDTH;
617 else if (screen_width < MINIMUM_SCREEN_WIDTH)
618 screen_width = MINIMUM_SCREEN_WIDTH;
619 if (screen_width != old_width)
621 bp->width = screen_width - 1;
622 bp->buffer = xrealloc (bp->buffer, bp->width + 1);
623 force_screen_update = true;
625 received_sigwinch = 0;
628 if (dltime - bp->last_screen_update < REFRESH_INTERVAL && !force_screen_update)
629 /* Don't update more often than five times per second. */
632 create_image (bp, dltime, false);
633 display_image (bp->buffer);
634 bp->last_screen_update = dltime;
638 bar_finish (void *progress, double dltime)
640 struct bar_progress *bp = progress;
642 if (bp->total_length > 0
643 && bp->count + bp->initial_length > bp->total_length)
644 /* See bar_update() for explanation. */
645 bp->total_length = bp->initial_length + bp->count;
647 create_image (bp, dltime, true);
648 display_image (bp->buffer);
650 logputs (LOG_VERBOSE, "\n\n");
656 /* This code attempts to maintain the notion of a "current" download
657 speed, over the course of no less than 3s. (Shorter intervals
658 produce very erratic results.)
660 To do so, it samples the speed in 150ms intervals and stores the
661 recorded samples in a FIFO history ring. The ring stores no more
662 than 20 intervals, hence the history covers the period of at least
663 three seconds and at most 20 reads into the past. This method
664 should produce reasonable results for downloads ranging from very
667 The idea is that for fast downloads, we get the speed over exactly
668 the last three seconds. For slow downloads (where a network read
669 takes more than 150ms to complete), we get the speed over a larger
670 time period, as large as it takes to complete thirty reads. This
671 is good because slow downloads tend to fluctuate more and a
672 3-second average would be too erratic. */
675 update_speed_ring (struct bar_progress *bp, wgint howmuch, double dltime)
677 struct bar_progress_hist *hist = &bp->hist;
678 double recent_age = dltime - bp->recent_start;
680 /* Update the download count. */
681 bp->recent_bytes += howmuch;
683 /* For very small time intervals, we return after having updated the
684 "recent" download count. When its age reaches or exceeds minimum
685 sample time, it will be recorded in the history ring. */
686 if (recent_age < DLSPEED_SAMPLE_MIN)
691 /* If we're not downloading anything, we might be stalling,
692 i.e. not downloading anything for an extended period of time.
693 Since 0-reads do not enter the history ring, recent_age
694 effectively measures the time since last read. */
695 if (recent_age >= STALL_START_TIME)
697 /* If we're stalling, reset the ring contents because it's
698 stale and because it will make bar_update stop printing
699 the (bogus) current bandwidth. */
702 bp->recent_bytes = 0;
707 /* We now have a non-zero amount of to store to the speed ring. */
709 /* If the stall status was acquired, reset it. */
713 /* "recent_age" includes the the entired stalled period, which
714 could be very long. Don't update the speed ring with that
715 value because the current bandwidth would start too small.
716 Start with an arbitrary (but more reasonable) time value and
721 /* Store "recent" bytes and download time to history ring at the
724 /* To correctly maintain the totals, first invalidate existing data
725 (least recent in time) at this position. */
726 hist->total_time -= hist->times[hist->pos];
727 hist->total_bytes -= hist->bytes[hist->pos];
729 /* Now store the new data and update the totals. */
730 hist->times[hist->pos] = recent_age;
731 hist->bytes[hist->pos] = bp->recent_bytes;
732 hist->total_time += recent_age;
733 hist->total_bytes += bp->recent_bytes;
735 /* Start a new "recent" period. */
736 bp->recent_start = dltime;
737 bp->recent_bytes = 0;
739 /* Advance the current ring position. */
740 if (++hist->pos == DLSPEED_HISTORY_SIZE)
744 /* Sledgehammer check to verify that the totals are accurate. */
747 double sumt = 0, sumb = 0;
748 for (i = 0; i < DLSPEED_HISTORY_SIZE; i++)
750 sumt += hist->times[i];
751 sumb += hist->bytes[i];
753 assert (sumb == hist->total_bytes);
754 /* We can't use assert(sumt==hist->total_time) because some
755 precision is lost by adding and subtracting floating-point
756 numbers. But during a download this precision should not be
757 detectable, i.e. no larger than 1ns. */
758 double diff = sumt - hist->total_time;
759 if (diff < 0) diff = -diff;
760 assert (diff < 1e-9);
765 #define APPEND_LITERAL(s) do { \
766 memcpy (p, s, sizeof (s) - 1); \
767 p += sizeof (s) - 1; \
770 /* Use move_to_end (s) to get S to point the end of the string (the
771 terminating \0). This is faster than s+=strlen(s), but some people
772 are confused when they see strchr (s, '\0') in the code. */
773 #define move_to_end(s) s = strchr (s, '\0');
776 # define MAX(a, b) ((a) >= (b) ? (a) : (b))
780 create_image (struct bar_progress *bp, double dl_total_time, bool done)
782 char *p = bp->buffer;
783 wgint size = bp->initial_length + bp->count;
785 const char *size_grouped = with_thousand_seps (size);
786 int size_grouped_len = strlen (size_grouped);
788 struct bar_progress_hist *hist = &bp->hist;
790 /* The progress bar should look like this:
791 xx% [=======> ] nn,nnn 12.34K/s eta 36m 51s
793 Calculate the geometry. The idea is to assign as much room as
794 possible to the progress bar. The other idea is to never let
795 things "jitter", i.e. pad elements that vary in size so that
796 their variance does not affect the placement of other elements.
797 It would be especially bad for the progress bar to be resized
800 "xx% " or "100%" - percentage - 4 chars
801 "[]" - progress bar decorations - 2 chars
802 " nnn,nnn,nnn" - downloaded bytes - 12 chars or very rarely more
803 " 12.5K/s" - download rate - 8 chars
804 " eta 36m 51s" - ETA - 13 chars
806 "=====>..." - progress bar - the rest
808 int dlbytes_size = 1 + MAX (size_grouped_len, 11);
809 int progress_size = bp->width - (4 + 2 + dlbytes_size + 8 + 13);
811 if (progress_size < 5)
815 if (bp->total_length > 0)
817 int percentage = 100.0 * size / bp->total_length;
818 assert (percentage <= 100);
820 if (percentage < 100)
821 sprintf (p, "%2d%% ", percentage);
827 APPEND_LITERAL (" ");
829 /* The progress bar: "[====> ]" or "[++==> ]". */
830 if (progress_size && bp->total_length > 0)
832 /* Size of the initial portion. */
833 int insz = (double)bp->initial_length / bp->total_length * progress_size;
835 /* Size of the downloaded portion. */
836 int dlsz = (double)size / bp->total_length * progress_size;
841 assert (dlsz <= progress_size);
842 assert (insz <= dlsz);
847 /* Print the initial portion of the download with '+' chars, the
848 rest with '=' and one '>'. */
849 for (i = 0; i < insz; i++)
854 for (i = 0; i < dlsz - 1; i++)
859 while (p - begin < progress_size)
863 else if (progress_size)
865 /* If we can't draw a real progress bar, then at least show
866 *something* to the user. */
867 int ind = bp->tick % (progress_size * 2 - 6);
870 /* Make the star move in two directions. */
871 if (ind < progress_size - 2)
874 pos = progress_size - (ind - progress_size + 5);
877 for (i = 0; i < progress_size; i++)
879 if (i == pos - 1) *p++ = '<';
880 else if (i == pos ) *p++ = '=';
881 else if (i == pos + 1) *p++ = '>';
891 sprintf (p, " %-11s", size_grouped);
895 if (hist->total_time > 0 && hist->total_bytes)
897 static const char *short_units[] = { "B/s", "K/s", "M/s", "G/s" };
899 /* Calculate the download speed using the history ring and
900 recent data that hasn't made it to the ring yet. */
901 wgint dlquant = hist->total_bytes + bp->recent_bytes;
902 double dltime = hist->total_time + (dl_total_time - bp->recent_start);
903 double dlspeed = calc_rate (dlquant, dltime, &units);
904 sprintf (p, " %4.*f%s", dlspeed >= 99.95 ? 0 : dlspeed >= 9.995 ? 1 : 2,
905 dlspeed, short_units[units]);
909 APPEND_LITERAL (" --.-K/s");
913 /* " eta ..m ..s"; wait for three seconds before displaying the ETA.
914 That's because the ETA value needs a while to become
916 if (bp->total_length > 0 && bp->count > 0 && dl_total_time > 3)
920 /* Don't change the value of ETA more than approximately once
921 per second; doing so would cause flashing without providing
922 any value to the user. */
923 if (bp->total_length != size
924 && bp->last_eta_value != 0
925 && dl_total_time - bp->last_eta_time < ETA_REFRESH_INTERVAL)
926 eta = bp->last_eta_value;
929 /* Calculate ETA using the average download speed to predict
930 the future speed. If you want to use a speed averaged
931 over a more recent period, replace dl_total_time with
932 hist->total_time and bp->count with hist->total_bytes.
933 I found that doing that results in a very jerky and
934 ultimately unreliable ETA. */
935 wgint bytes_remaining = bp->total_length - size;
936 double eta_ = dl_total_time * bytes_remaining / bp->count;
937 if (eta_ >= INT_MAX - 1)
939 eta = (int) (eta_ + 0.5);
940 bp->last_eta_value = eta;
941 bp->last_eta_time = dl_total_time;
944 /* Translation note: "ETA" is English-centric, but this must
945 be short, ideally 3 chars. Abbreviate if necessary. */
946 sprintf (p, _(" eta %s"), eta_to_human_short (eta, false));
949 else if (bp->total_length > 0)
952 APPEND_LITERAL (" ");
957 /* When the download is done, print the elapsed time. */
959 /* Note to translators: this should not take up more room than
960 available here. Abbreviate if necessary. */
961 strcpy (p, _(" in "));
962 move_to_end (p); /* not p+=6, think translations! */
963 if (dl_total_time >= 10)
964 strcpy (p, eta_to_human_short ((int) (dl_total_time + 0.5), false));
966 sprintf (p, "%ss", print_decimal (dl_total_time));
970 assert (p - bp->buffer <= bp->width);
972 while (p < bp->buffer + bp->width)
977 /* Print the contents of the buffer as a one-line ASCII "image" so
978 that it can be overwritten next time. */
981 display_image (char *buf)
983 bool old = log_set_save_context (false);
984 logputs (LOG_VERBOSE, "\r");
985 logputs (LOG_VERBOSE, buf);
986 log_set_save_context (old);
990 bar_set_params (const char *params)
992 char *term = getenv ("TERM");
995 && 0 == strcmp (params, "force"))
996 current_impl_locked = 1;
1000 /* The progress bar doesn't make sense if the output is not a
1001 TTY -- when logging to file, it is better to review the
1003 || !isatty (fileno (stderr))
1005 /* Normally we don't depend on terminal type because the
1006 progress bar only uses ^M to move the cursor to the
1007 beginning of line, which works even on dumb terminals. But
1008 Jamie Zawinski reports that ^M and ^H tricks don't work in
1009 Emacs shell buffers, and only make a mess. */
1010 || (term && 0 == strcmp (term, "emacs"))
1012 && !current_impl_locked)
1014 /* We're not printing to a TTY, so revert to the fallback
1015 display. #### We're recursively calling
1016 set_progress_implementation here, which is slightly kludgy.
1017 It would be nicer if we provided that function a return value
1018 indicating a failure of some sort. */
1019 set_progress_implementation (FALLBACK_PROGRESS_IMPLEMENTATION);
1026 progress_handle_sigwinch (int sig)
1028 received_sigwinch = 1;
1029 signal (SIGWINCH, progress_handle_sigwinch);
1033 /* Provide a short human-readable rendition of the ETA. This is like
1034 secs_to_human_time in main.c, except the output doesn't include
1035 fractions (which would look silly in by nature imprecise ETA) and
1036 takes less room. If the time is measured in hours, hours and
1037 minutes (but not seconds) are shown; if measured in days, then days
1038 and hours are shown. This ensures brevity while still displaying
1039 as much as possible.
1041 If CONDENSED is true, the separator between minutes and seconds
1042 (and hours and minutes, etc.) is not included, shortening the
1043 display by one additional character. This is used for dot
1046 The display never occupies more than 7 characters of screen
1050 eta_to_human_short (int secs, bool condensed)
1052 static char buf[10]; /* 8 should be enough, but just in case */
1053 static int last = -1;
1054 const char *space = condensed ? "" : " ";
1056 /* Trivial optimization. create_image can call us every 200 msecs
1057 (see bar_update) for fast downloads, but ETA will only change
1058 once per 900 msecs. */
1064 sprintf (buf, "%ds", secs);
1065 else if (secs < 100 * 60)
1066 sprintf (buf, "%dm%s%ds", secs / 60, space, secs % 60);
1067 else if (secs < 48 * 3600)
1068 sprintf (buf, "%dh%s%dm", secs / 3600, space, (secs / 60) % 60);
1069 else if (secs < 100 * 86400)
1070 sprintf (buf, "%dd%s%dh", secs / 86400, space, (secs / 3600) % 60);
1072 /* even (2^31-1)/86400 doesn't overflow BUF. */
1073 sprintf (buf, "%dd", secs / 86400);