1/*	$NetBSD: progressbar.c,v 1.21 2009/04/12 10:18:52 lukem Exp $	*/
2
3/*-
4 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Luke Mewburn.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include <sys/types.h>
33#include <sys/param.h>
34#include <sys/ioctl.h>
35
36#include <errno.h>
37#include <stdio.h>
38#include <stdlib.h>
39#include <string.h>
40#include <termios.h>
41#include <time.h>
42#include <unistd.h>
43
44#include <sys/cdefs.h>
45__FBSDID("$FreeBSD$");
46
47#include "progress.h"
48
49static const char * const suffixes[] = {
50	"",	/* 2^0  (byte) */
51	"KiB",	/* 2^10 Kibibyte */
52	"MiB",	/* 2^20 Mebibyte */
53	"GiB",	/* 2^30 Gibibyte */
54	"TiB",	/* 2^40 Tebibyte */
55	"PiB",	/* 2^50 Pebibyte */
56	"EiB",	/* 2^60 Exbibyte */
57};
58
59#define NSUFFIXES	(sizeof(suffixes) / sizeof(suffixes[0]))
60#define SECSPERHOUR	(60 * 60)
61#define DEFAULT_TTYWIDTH	80
62
63/* initialise progress meter structure */
64int
65progress_init(progress_t *prog, const char *prefix, uint64_t total)
66{
67        struct winsize	winsize;
68        int		oerrno = errno;
69
70	(void) memset(prog, 0x0, sizeof(*prog));
71	prog->size = total;
72	prog->prefix = strdup(prefix);
73	prog->start = time(NULL);
74        if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize) != -1 &&
75            winsize.ws_col != 0) {
76                prog->ttywidth = winsize.ws_col;
77        } else {
78                prog->ttywidth = DEFAULT_TTYWIDTH;
79	}
80        errno = oerrno;
81	return 1;
82}
83
84/* update the values in the progress meter */
85int
86progress_update(progress_t *prog, uint64_t done)
87{
88	prog->done = done;
89	prog->percent = (prog->done * 100) / prog->size;
90	prog->now = time(NULL);
91	prog->elapsed = prog->now - prog->start;
92	if (done == 0 || prog->elapsed == 0 || prog->done / prog->elapsed == 0) {
93		prog->eta = 0;
94	} else {
95		prog->eta = prog->size / (prog->done / prog->elapsed) - prog->elapsed;
96	}
97	return 1;
98}
99
100/* update the values in the progress meter */
101int
102progress_reset_size(progress_t *prog, uint64_t size)
103{
104	prog->size = size;
105	return 1;
106}
107
108/* make it look pretty at the end - display done bytes (usually total) */
109int
110progress_complete(progress_t *prog, uint64_t done)
111{
112	progress_update(prog, done);
113	progress_draw(prog);
114	printf("\n");
115	return 1;
116}
117
118/* draw the progress meter */
119int
120progress_draw(progress_t *prog)
121{
122#define	BAROVERHEAD	45		/* non `*' portion of progress bar */
123					/*
124					 * stars should contain at least
125					 * sizeof(buf) - BAROVERHEAD entries
126					 */
127	static const char	stars[] =
128"*****************************************************************************"
129"*****************************************************************************"
130"*****************************************************************************";
131	unsigned		bytesabbrev;
132	unsigned		bpsabbrev;
133	int64_t			secs;
134	uint64_t		bytespersec;
135	uint64_t		abbrevsize;
136	int64_t			secsleft;
137	size_t			barlength;
138	size_t			starc;
139	char			hours[12];
140	char			buf[256];
141	int			len;
142
143	barlength = MIN(sizeof(buf) - 1, (unsigned)prog->ttywidth) - BAROVERHEAD - strlen(prog->prefix);
144	starc = (barlength * prog->percent) / 100;
145	abbrevsize = prog->done;
146	for (bytesabbrev = 0; abbrevsize >= 100000 && bytesabbrev < NSUFFIXES; bytesabbrev++) {
147		abbrevsize >>= 10;
148	}
149	if (bytesabbrev == NSUFFIXES) {
150		bytesabbrev--;
151	}
152	bytespersec = 0;
153	if (prog->done > 0) {
154		bytespersec = prog->done;
155		if (prog->elapsed > 0) {
156			bytespersec /= prog->elapsed;
157		}
158	}
159	for (bpsabbrev = 1; bytespersec >= 1024000 && bpsabbrev < NSUFFIXES; bpsabbrev++) {
160		bytespersec >>= 10;
161	}
162	if (prog->done == 0 || prog->elapsed <= 0 || prog->done > prog->size) {
163		secsleft = 0;
164	} else {
165		secsleft = prog->eta;
166	}
167	if ((secs = secsleft / SECSPERHOUR) > 0) {
168		(void) snprintf(hours, sizeof(hours), "%2lld:", (long long)secs);
169	} else {
170		(void) snprintf(hours, sizeof(hours), "   ");
171	}
172	secs = secsleft % SECSPERHOUR;
173	len = snprintf(buf, sizeof(buf),
174		"\r%s %3lld%% |%.*s%*s| %5lld %-3s %3lld.%02d %.2sB/s %s%02d:%02d ETA",
175		(prog->prefix) ? prog->prefix : "",
176		(long long)prog->percent,
177		(int)starc, stars, (int)(barlength - starc), "",
178		(long long)abbrevsize,
179		suffixes[bytesabbrev],
180		(long long)(bytespersec / 1024),
181		(int)((bytespersec % 1024) * 100 / 1024),
182		suffixes[bpsabbrev],
183		hours,
184		(int)secs / 60, (int)secs % 60);
185	return (int)write(STDOUT_FILENO, buf, len);
186}
187