fish: Make progress bars into a mini library.
[libguestfs.git] / fish / progress.c
1 /* libguestfs - mini library for progress bars.
2  * Copyright (C) 2010-2011 Red Hat Inc.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17  */
18
19 #include <config.h>
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <inttypes.h>
25 #include <math.h>
26 #include <sys/time.h>
27 #include <langinfo.h>
28
29 #include "progress.h"
30
31 /* Include these last since they redefine symbols such as 'lines'
32  * which seriously breaks other headers.
33  */
34 #include <term.h>
35 #include <curses.h>
36
37 /* Provided by termcap or terminfo emulation, but not defined
38  * in any header file.
39  */
40 extern const char *UP;
41
42 #define STREQ(a,b) (strcmp((a),(b)) == 0)
43
44 /* Compute the running mean and standard deviation from the
45  * series of estimated values.
46  *
47  * Method:
48  * http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods
49  * Checked in a test program against answers given by Wolfram Alpha.
50  */
51 struct rmsd {
52   double a;                     /* mean */
53   double i;                     /* number of samples */
54   double q;
55 };
56
57 static void
58 rmsd_init (struct rmsd *r)
59 {
60   r->a = 0;
61   r->i = 1;
62   r->q = 0;
63 }
64
65 static void
66 rmsd_add_sample (struct rmsd *r, double x)
67 {
68   double a_next, q_next;
69
70   a_next = r->a + (x - r->a) / r->i;
71   q_next = r->q + (x - r->a) * (x - a_next);
72   r->a = a_next;
73   r->q = q_next;
74   r->i += 1.0;
75 }
76
77 static double
78 rmsd_get_mean (const struct rmsd *r)
79 {
80   return r->a;
81 }
82
83 static double
84 rmsd_get_standard_deviation (const struct rmsd *r)
85 {
86   return sqrt (r->q / (r->i - 1.0));
87 }
88
89 struct progress_bar {
90   double start;         /* start time of command */
91   int count;            /* number of progress notifications per cmd */
92   struct rmsd rmsd;     /* running mean and standard deviation */
93   int have_terminfo;
94   int utf8_mode;
95 };
96
97 struct progress_bar *
98 progress_bar_init (unsigned flags)
99 {
100   struct progress_bar *bar;
101   char *term;
102
103   bar = malloc (sizeof *bar);
104   if (bar == NULL)
105     return NULL;
106
107   bar->utf8_mode = STREQ (nl_langinfo (CODESET), "UTF-8");
108
109   bar->have_terminfo = 0;
110
111   term = getenv ("TERM");
112   if (term) {
113     if (tgetent (NULL, term) == 1)
114       bar->have_terminfo = 1;
115   }
116
117   /* Call this to ensure the other fields are in a reasonable state.
118    * It is still the caller's responsibility to reset the progress bar
119    * before each command.
120    */
121   progress_bar_reset (bar);
122
123   return bar;
124 }
125
126 void
127 progress_bar_free (struct progress_bar *bar)
128 {
129   free (bar);
130 }
131
132 /* This function is called just before we issue any command. */
133 void
134 progress_bar_reset (struct progress_bar *bar)
135 {
136   /* The time at which this command was issued. */
137   struct timeval start_t;
138   gettimeofday (&start_t, NULL);
139
140   bar->start = start_t.tv_sec + start_t.tv_usec / 1000000.;
141
142   bar->count = 0;
143
144   rmsd_init (&bar->rmsd);
145 }
146
147 static const char *
148 spinner (struct progress_bar *bar, int count)
149 {
150   /* Choice of unicode spinners.
151    *
152    * For basic dingbats, see:
153    * http://www.fileformat.info/info/unicode/block/geometric_shapes/utf8test.htm
154    * http://www.fileformat.info/info/unicode/block/dingbats/utf8test.htm
155    *
156    * Arrows are a mess in unicode.  This page helps a lot:
157    * http://xahlee.org/comp/unicode_arrows.html
158    *
159    * I prefer something which doesn't point, just spins.
160    */
161   /* Black pointing triangle. */
162   //static const char *us[] = { "\u25b2", "\u25b6", "\u25bc", "\u25c0" };
163   /* White pointing triangle. */
164   //static const char *us[] = { "\u25b3", "\u25b7", "\u25bd", "\u25c1" };
165   /* Circle with half black. */
166   static const char *us[] = { "\u25d0", "\u25d3", "\u25d1", "\u25d2" };
167   /* White square white quadrant. */
168   //static const char *us[] = { "\u25f0", "\u25f3", "\u25f2", "\u25f1" };
169   /* White circle white quadrant. */
170   //static const char *us[] = { "\u25f4", "\u25f7", "\u25f6", "\u25f5" };
171   /* Black triangle. */
172   //static const char *us[] = { "\u25e2", "\u25e3", "\u25e4", "\u25e5" };
173   /* Spinning arrow in 8 directions. */
174   //static const char *us[] = { "\u2190", "\u2196", "\u2191", "\u2197",
175   //                            "\u2192", "\u2198", "\u2193", "\u2199" };
176
177   /* ASCII spinner. */
178   static const char *as[] = { "/", "-", "\\", "|" };
179
180   const char **s;
181   size_t n;
182
183   if (bar->utf8_mode) {
184     s = us;
185     n = sizeof us / sizeof us[0];
186   }
187   else {
188     s = as;
189     n = sizeof as / sizeof as[0];
190   }
191
192   return s[count % n];
193 }
194
195 /* Return remaining time estimate (in seconds) for current call.
196  *
197  * This returns the running mean estimate of remaining time, but if
198  * the latest estimate of total time is greater than two s.d.'s from
199  * the running mean then we don't print anything because we're not
200  * confident that the estimate is meaningful.  (Returned value is <0.0
201  * when nothing should be printed).
202  */
203 static double
204 estimate_remaining_time (struct progress_bar *bar, double ratio)
205 {
206   if (ratio <= 0.)
207     return -1.0;
208
209   struct timeval now_t;
210   gettimeofday (&now_t, NULL);
211
212   double now = now_t.tv_sec + now_t.tv_usec / 1000000.;
213   /* We've done 'ratio' of the work in 'now - start' seconds. */
214   double time_passed = now - bar->start;
215
216   double total_time = time_passed / ratio;
217
218   /* Add total_time to running mean and s.d. and then see if our
219    * estimate of total time is meaningful.
220    */
221   rmsd_add_sample (&bar->rmsd, total_time);
222
223   double mean = rmsd_get_mean (&bar->rmsd);
224   double sd = rmsd_get_standard_deviation (&bar->rmsd);
225   if (fabs (total_time - mean) >= 2.0*sd)
226     return -1.0;
227
228   /* Don't return early estimates. */
229   if (time_passed < 3.0)
230     return -1.0;
231
232   return total_time - time_passed;
233 }
234
235 /* The overhead is how much we subtract before we get to the progress
236  * bar itself.
237  *
238  * / 100% [########---------------] xx:xx
239  * | |    |                       | |
240  * | |    |                       | time (5 cols)
241  * | |    |                       |
242  * | |    open paren + close paren + space (3 cols)
243  * | |
244  * | percentage and space (5 cols)
245  * |
246  * spinner and space (2 cols)
247  *
248  * Total = 2 + 5 + 3 + 5 = 15
249  */
250 #define COLS_OVERHEAD 15
251
252 void
253 progress_bar_set (struct progress_bar *bar,
254                   uint64_t position, uint64_t total)
255 {
256   int i, cols, pulse_mode;
257   double ratio;
258   const char *s_open, *s_dot, *s_dash, *s_close;
259
260   if (bar->utf8_mode) {
261     s_open = "\u27e6"; s_dot = "\u2589"; s_dash = "\u2550"; s_close = "\u27e7";
262   } else {
263     s_open = "["; s_dot = "#"; s_dash = "-"; s_close = "]";
264   }
265
266   if (bar->have_terminfo == 0) {
267   dumb:
268     printf ("%" PRIu64 "/%" PRIu64 "\n", position, total);
269   } else {
270     cols = tgetnum ((char *) "co");
271     if (cols < 32) goto dumb;
272
273     /* Update an existing progress bar just printed? */
274     if (bar->count > 0)
275       tputs (UP, 2, putchar);
276     bar->count++;
277
278     /* Find out if we're in "pulse mode". */
279     pulse_mode = position == 0 && total == 1;
280
281     ratio = (double) position / total;
282     if (ratio < 0) ratio = 0; else if (ratio > 1) ratio = 1;
283
284     if (pulse_mode) {
285       printf ("%s --- ", spinner (bar, bar->count));
286     }
287     else if (ratio < 1) {
288       int percent = 100.0 * ratio;
289       printf ("%s%3d%% ", spinner (bar, bar->count), percent);
290     }
291     else {
292       fputs (" 100% ", stdout);
293     }
294
295     fputs (s_open, stdout);
296
297     if (!pulse_mode) {
298       int dots = ratio * (double) (cols - COLS_OVERHEAD);
299
300       for (i = 0; i < dots; ++i)
301         fputs (s_dot, stdout);
302       for (i = dots; i < cols - COLS_OVERHEAD; ++i)
303         fputs (s_dash, stdout);
304     }
305     else {           /* "Pulse mode": the progress bar just pulses. */
306       for (i = 0; i < cols - COLS_OVERHEAD; ++i) {
307         int cc = (bar->count * 3 - i) % (cols - COLS_OVERHEAD);
308         if (cc >= 0 && cc <= 3)
309           fputs (s_dot, stdout);
310         else
311           fputs (s_dash, stdout);
312       }
313     }
314
315     fputs (s_close, stdout);
316     fputc (' ', stdout);
317
318     /* Time estimate. */
319     double estimate = estimate_remaining_time (bar, ratio);
320     if (estimate >= 100.0 * 60.0 * 60.0 /* >= 100 hours */) {
321       /* Display hours<h> */
322       estimate /= 60. * 60.;
323       int hh = floor (estimate);
324       printf (">%dh", hh);
325     } else if (estimate >= 100.0 * 60.0 /* >= 100 minutes */) {
326       /* Display hours<h>minutes */
327       estimate /= 60. * 60.;
328       int hh = floor (estimate);
329       double ignore;
330       int mm = floor (modf (estimate, &ignore) * 60.);
331       printf ("%02dh%02d", hh, mm);
332     } else if (estimate >= 0.0) {
333       /* Display minutes:seconds */
334       estimate /= 60.;
335       int mm = floor (estimate);
336       double ignore;
337       int ss = floor (modf (estimate, &ignore) * 60.);
338       printf ("%02d:%02d", mm, ss);
339     }
340     else /* < 0 means estimate was not meaningful */
341       fputs ("--:--", stdout);
342
343     fputc ('\n', stdout);
344   }
345 }