/
progress_bar.c
123 lines (99 loc) · 2.45 KB
/
progress_bar.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include "pushtf-client.h"
typedef struct {
double b;
char *unit;
} human_unit_t;
static void bytes_to_unit(human_unit_t *h, off_t bytes)
{
char *units[] = {"B", "KB", "MB", "GB", "TB"};
char p = 0;
h->b = bytes;
if (bytes)
while (h->b/1024 > 1 && p < 4) {
h->b /= 1024;
p++;
}
h->unit = units[(unsigned char)p];
}
static void print_eta(time_t sec)
{
long hr, min, t;
hr = sec/3600;
t = sec%3600;
min = t/60;
sec = t%60;
if (hr) {
printf("%02ld:%02ld.%02ld", hr, min, sec);
} else if (min) {
printf("00:%02ld.%02ld", min, sec);
} else if (sec) {
printf("%2ld sec", sec);
}
}
static void print_progress_bar(int percent, off_t pos, unsigned long speed, time_t eta)
{
int i;
human_unit_t h;
struct winsize w;
int progress_bar_length;
int prgbar_stars;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
progress_bar_length = w.ws_col - 7 - 38;
prgbar_stars = (int)((percent * progress_bar_length) / 100);
printf("\033[2K\r%3d %% [", percent);
for (i = 0; i++ < prgbar_stars; printf("*"));
for (; i++ < progress_bar_length; printf(" "));
if (percent == 100) {
#if defined(__i386__) || defined(__arm__) || defined(__APPLE__)
printf("] %llu bytes", pos);
#else
printf("] %lu bytes", pos);
#endif
} else {
bytes_to_unit(&h, pos);
printf("] %.3f %s", h.b, h.unit);
if (speed) {
bytes_to_unit(&h, speed);
printf(" - %.0f %s/s", h.b, h.unit);
}
if (eta) {
printf(" ETA ");
print_eta(eta);
}
}
}
void progress_bar(sfile_t *f)
{
time_t tick;
unsigned long speed;
int percent;
human_unit_t h;
off_t filesize = 0;
if (g_quiet)
return;
if (f->fd)
filesize = f->st.st_size ? f->st.st_size : f->h->content_length;
tick = time(NULL);
if (f->fh_cur_pos == filesize) {
print_progress_bar(100, f->fh_cur_pos, 0, 0);
}
else
if (f->speedometer == 0 || tick >= f->pb_timer + 1)
{
f->pb_timer = time(NULL);
speed = f->fh_cur_pos - f->speedometer;
f->speedometer = f->fh_cur_pos;
if (filesize) {
percent = (int)(f->fh_cur_pos * 100 / filesize);
print_progress_bar(percent, f->fh_cur_pos, speed,
(filesize - f->fh_cur_pos) / speed);
} else {
bytes_to_unit(&h, speed);
#if defined(__i386__) || defined(__arm__) || defined(__APPLE__)
printf("\033[2K\r%llu bytes - %.0f %s/s", f->fh_cur_pos, h.b, h.unit);
#else
printf("\033[2K\r%lu bytes - %.0f %s/s", f->fh_cur_pos, h.b, h.unit);
#endif
}
}
}