diff --git a/src/util.c b/src/util.c index 7f98d17c..a2a3d623 100644 --- a/src/util.c +++ b/src/util.c @@ -21,10 +21,17 @@ * THE SOFTWARE. */ +#include "config.h" #include /* isprint() */ #include #include +#ifdef HAVE_TERMIOS_H /* for screen_width() */ +#include +#include +#include +#endif + char *prognm = NULL; char *progname(char *arg0) @@ -69,6 +76,36 @@ char *sanitize(char *arg, size_t len) return NULL; } +#define ESC "\033" +int screen_width(void) +{ + int ret = 80; +#ifdef HAVE_TERMIOS_H + char buf[42]; + struct termios tc, saved; + struct pollfd fd = { STDIN_FILENO, POLLIN, 0 }; + + memset(buf, 0, sizeof(buf)); + tcgetattr(STDERR_FILENO, &tc); + saved = tc; + tc.c_cflag |= (CLOCAL | CREAD); + tc.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); + tcsetattr(STDERR_FILENO, TCSANOW, &tc); + fprintf(stderr, ESC "7" ESC "[r" ESC "[999;999H" ESC "[6n"); + + if (poll(&fd, 1, 300) > 0) { + int row, col; + + if (scanf(ESC "[%d;%dR", &row, &col) == 2) + ret = col; + } + + fprintf(stderr, ESC "8"); + tcsetattr(STDERR_FILENO, TCSANOW, &saved); +#endif + return ret; +} + /** * Local Variables: * indent-tabs-mode: t diff --git a/src/util.h b/src/util.h index ef522415..4f913e42 100644 --- a/src/util.h +++ b/src/util.h @@ -1,6 +1,6 @@ /* Misc. shared utility functions for initctl, reboot and finit * - * Copyright (c) 2016 Joachim Nilsson + * Copyright (c) 2016-2017 Joachim Nilsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal @@ -26,9 +26,10 @@ extern char *prognm; -char *progname(char *arg0); -void do_sleep(unsigned int sec); -char *sanitize(char *arg, size_t len); +char *progname (char *arg0); +void do_sleep (unsigned int sec); +char *sanitize (char *arg, size_t len); +int screen_width (void); #endif /* FINIT_UTIL_H_ */