libite 2.6.1
progress.c
Go to the documentation of this file.
1/* Simple termios based progress bar
2 *
3 * Copyright (c) 2012-2021 Joachim Wiberg <troglobit@gmail.com>
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
24
25#include <limits.h> /* INT_MAX */
26#include <stdio.h>
27#include <string.h>
28
29#include "conio.h"
30
31#define SPINNER_THROB ".oOo"
32#define SPINNER_PULSAR ".oO°Oo."
33#define SPINNER_ARROW "v<^>"
34#define SPINNER_STAR ".oO@*"
35#define SPINNER_DEFAULT "|/-\\"
36
37static char spinner(char *style)
38{
39 size_t num;
40 static unsigned int i = 0;
41
42 if (!style)
43 style = SPINNER_DEFAULT;
44 num = strlen(style);
45
46 return style[i++ % num]; /* % Number of states in style */
47}
48
66void progress(int percent, int max_width)
67{
68 int i, bar;
69
70 /* Adjust for progress bar overhead */
71 max_width -= 10;
72
73 if (0 == percent)
74 hidecursor();
75
76 fprintf(stderr, "\r%3d%% %c [", percent, spinner(NULL));
77
78 bar = percent * max_width / 100;
79 for (i = 0; i < max_width; i++) {
80 if (i > bar)
81 fputc(' ', stderr);
82 else if (i == bar)
83 fputc('>', stderr);
84 else
85 fputc('=', stderr);
86 }
87
88 fprintf(stderr, "]");
89 if (100 == percent) {
90 showcursor();
91 fputc('\n', stderr);
92 }
93}
94
99void progress_simple(int percent)
100{
101 static int last = 1;
102 int ratio, numout;
103
104 if (!percent && last) {
105 last = 0;
106 fputs("0% 25% 50% 75% 100%\n"
107 "|---------+---------+---------+---------|\n"
108 "|", stderr);
109 return;
110 }
111
112 ratio = 40 * percent / 100;
113 numout = ratio - last;
114
115 if (ratio <= last)
116 return;
117
118 last = ratio;
119
120 while (numout--) {
121 if (ratio != 40 || numout)
122 putc('=', stderr);
123 else
124 putc('|', stderr);
125 }
126}
127
#define showcursor()
Definition conio.h:80
#define hidecursor()
Definition conio.h:78
void progress(int percent, int max_width)
Definition progress.c:66
void progress_simple(int percent)
Definition progress.c:99