1/*	$NetBSD: progressbar.c,v 1.21 2009/04/12 10:18:52 lukem Exp $	*/
2
3/*-
4 * SPDX-License-Identifier: BSD-2-Clause
5 *
6 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
7 * All rights reserved.
8 *
9 * This code is derived from software contributed to The NetBSD Foundation
10 * by Luke Mewburn.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
32 */
33
34#include <sys/types.h>
35#include <sys/param.h>
36#include <sys/ioctl.h>
37
38#include <errno.h>
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <termios.h>
43#include <time.h>
44#include <unistd.h>
45
46#include <sys/cdefs.h>
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	nitems(suffixes)
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#define	MIN_BAR_LEN	10
128	static const char	stars[] =
129"*****************************************************************************"
130"*****************************************************************************"
131"*****************************************************************************";
132	unsigned		bytesabbrev;
133	unsigned		bpsabbrev;
134	int64_t			secs;
135	uint64_t		bytespersec;
136	uint64_t		abbrevsize;
137	int64_t			secsleft;
138	ssize_t			barlength;
139	size_t			starc;
140	char			hours[12];
141	char			buf[256];
142	int			len;
143	int			prefix_len;
144
145	prefix_len = strlen(prog->prefix);
146	barlength = MIN(sizeof(buf) - 1, (unsigned)prog->ttywidth) -
147		BAROVERHEAD - prefix_len;
148	if (barlength < MIN_BAR_LEN) {
149		int tmp_prefix_len;
150		/*
151		 * In this case the TTY width is too small or the prefix is
152		 * too large for a progress bar.  We'll try decreasing the
153		 * prefix length.
154		 */
155		barlength = MIN_BAR_LEN;
156		tmp_prefix_len = MIN(sizeof(buf) - 1,(unsigned)prog->ttywidth) -
157		    BAROVERHEAD - MIN_BAR_LEN;
158		if (tmp_prefix_len > 0)
159			prefix_len = tmp_prefix_len;
160		else
161			prefix_len = 0;
162	}
163	starc = (barlength * prog->percent) / 100;
164	abbrevsize = prog->done;
165	for (bytesabbrev = 0; abbrevsize >= 100000 && bytesabbrev < NSUFFIXES; bytesabbrev++) {
166		abbrevsize >>= 10;
167	}
168	if (bytesabbrev == NSUFFIXES) {
169		bytesabbrev--;
170	}
171	bytespersec = 0;
172	if (prog->done > 0) {
173		bytespersec = prog->done;
174		if (prog->elapsed > 0) {
175			bytespersec /= prog->elapsed;
176		}
177	}
178	for (bpsabbrev = 1; bytespersec >= 1024000 && bpsabbrev < NSUFFIXES; bpsabbrev++) {
179		bytespersec >>= 10;
180	}
181	if (prog->done == 0 || prog->elapsed <= 0 || prog->done > prog->size) {
182		secsleft = 0;
183	} else {
184		secsleft = prog->eta;
185	}
186	if ((secs = secsleft / SECSPERHOUR) > 0) {
187		(void) snprintf(hours, sizeof(hours), "%2lld:", (long long)secs);
188	} else {
189		(void) snprintf(hours, sizeof(hours), "   ");
190	}
191	secs = secsleft % SECSPERHOUR;
192	len = snprintf(buf, sizeof(buf),
193		"\r%.*s %3lld%% |%.*s%*s| %5lld %-3s %3lld.%02d %.2sB/s %s%02d:%02d ETA",
194		prefix_len, (prog->prefix) ? prog->prefix : "",
195		(long long)prog->percent,
196		(int)starc, stars, (int)(barlength - starc), "",
197		(long long)abbrevsize,
198		suffixes[bytesabbrev],
199		(long long)(bytespersec / 1024),
200		(int)((bytespersec % 1024) * 100 / 1024),
201		suffixes[bpsabbrev],
202		hours,
203		(int)secs / 60, (int)secs % 60);
204	return (int)write(STDOUT_FILENO, buf, len);
205}
206