|
| 1 | +#include <stdlib.h> |
| 2 | +#include <unistd.h> |
| 3 | +#include <pthread.h> |
| 4 | +#include <string.h> |
| 5 | +#include <termios.h> |
| 6 | +#include <signal.h> |
| 7 | +#include <stdio.h> |
| 8 | +#include "progressbar.h" |
| 9 | +#include "status.h" |
| 10 | +#include "const.h" |
| 11 | +#include "error.h" |
| 12 | + |
| 13 | +#define BUF_SIZE (1024) |
| 14 | + |
| 15 | +static struct termios g_old_tio, g_new_tio; |
| 16 | + |
| 17 | +static pthread_t g_pbarthread_id = 0; |
| 18 | +static volatile sig_atomic_t g_pbarthread_running = 1; |
| 19 | + |
| 20 | + |
| 21 | +/** thread worker |
| 22 | + * print progression status with print_status() on keypress |
| 23 | + */ |
| 24 | +#define SLEEPTIME_MS 250 // pbar refresh frequency |
| 25 | +#define ITER 25 // 25 loop iterations per loop refresh |
| 26 | +static void *progressbar_worker(void *arg) |
| 27 | +{ |
| 28 | + (void)arg; |
| 29 | + int iter = ITER; |
| 30 | + while (g_pbarthread_running) |
| 31 | + { |
| 32 | + if (iter == ITER) { |
| 33 | + display_status(0); |
| 34 | + iter = 0; |
| 35 | + } |
| 36 | + usleep((SLEEPTIME_MS * 1000) / ITER); // 250ms / iter |
| 37 | + ++iter; |
| 38 | + } |
| 39 | + display_status(1); |
| 40 | + return NULL; |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +/** restore terminal's line buffering & echo |
| 45 | + */ |
| 46 | +static void restore_termios(void) |
| 47 | +{ |
| 48 | + tcsetattr(STDERR_FILENO, TCSANOW, &g_old_tio); |
| 49 | +} |
| 50 | + |
| 51 | +/** disable terminal's line buffering & echo |
| 52 | + */ |
| 53 | +static void config_termios(void) |
| 54 | +{ |
| 55 | + if (tcgetattr(STDERR_FILENO, &g_old_tio) < 0) |
| 56 | + error("tcgetattr(): %s", ERRNO); |
| 57 | + |
| 58 | + g_new_tio = g_old_tio; |
| 59 | + g_new_tio.c_lflag &= ~(ICANON | ECHO); |
| 60 | + |
| 61 | + if (tcsetattr(STDERR_FILENO, TCSANOW, &g_new_tio) < 0) |
| 62 | + error("tcsetattr(): %s", ERRNO); |
| 63 | + |
| 64 | + atexit(restore_termios); |
| 65 | +} |
| 66 | + |
| 67 | + |
| 68 | +void start_progressbar(void) |
| 69 | +{ |
| 70 | + if (!isatty(STDERR_FILENO)) |
| 71 | + return ; |
| 72 | + |
| 73 | + /* Ignore if not in foreground */ |
| 74 | + if (tcgetpgrp(STDERR_FILENO) != getpgrp()) |
| 75 | + return; |
| 76 | + |
| 77 | + config_termios(); |
| 78 | + if (pthread_create( |
| 79 | + &g_pbarthread_id, NULL, |
| 80 | + &progressbar_worker, NULL |
| 81 | + ) < 0) { |
| 82 | + error("cannot create watch_user_input_worker() thread: %s", ERRNO); |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +void stop_progressbar(void) |
| 87 | +{ |
| 88 | + if (g_pbarthread_id == 0) |
| 89 | + return; |
| 90 | + g_pbarthread_running = 0; |
| 91 | + pthread_join(g_pbarthread_id, NULL); // wait thread (ignored if already detached) |
| 92 | + restore_termios(); |
| 93 | + g_pbarthread_id = 0; |
| 94 | +} |
0 commit comments