Refactor screen_init(), preparing for migration to libite

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
This commit is contained in:
Joachim Nilsson committed 2017-07-07 23:00:27 +02:00
1 parent 99f3f0291a
commit 0b43d0dc70
1 file changed
+33 -29
+33 -29
View File
@@ -32,7 +32,6 @@
#include <termios.h> #include <termios.h>
#endif #endif
int screen_setup = -1;
int screen_rows = 24; int screen_rows = 24;
int screen_cols = 80; int screen_cols = 80;
char *prognm = NULL; char *prognm = NULL;
@@ -79,51 +78,56 @@ char *sanitize(char *arg, size_t len)
return NULL; return NULL;
} }
#define ESC "\033" static void initscr(int *row, int *col)
void screen_init(void)
{ {
#ifdef HAVE_TERMIOS_H if (!row || !col)
char buf[42]; return;
#if defined(TCSANOW) && defined(POLLIN)
struct termios tc, saved; struct termios tc, saved;
struct pollfd fd = { STDIN_FILENO, POLLIN, 0 }; struct pollfd fd = { STDIN_FILENO, POLLIN, 0 };
if (screen_setup != -1) /* Disable echo to terminal while probing */
return;
memset(buf, 0, sizeof(buf));
tcgetattr(STDERR_FILENO, &tc); tcgetattr(STDERR_FILENO, &tc);
saved = tc; saved = tc;
tc.c_cflag |= (CLOCAL | CREAD); tc.c_cflag |= (CLOCAL | CREAD);
tc.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); tc.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tcsetattr(STDERR_FILENO, TCSANOW, &tc); 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; * Save cursor pos+attr
* Diable top+bottom margins
* Set cursor at the far bottom,right pos
* Query term for resulting pos
*/
fprintf(stderr, "\e7" "\e[r" "\e[999;999H" "\e[6n");
if (scanf(ESC "[%d;%dR", &row, &col) == 2) { /*
screen_rows = row; * Wait here for terminal to echo back \e[row,lineR ...
screen_cols = col; */
screen_setup = 1; if (poll(&fd, 1, 300) <= 0 || scanf("\e[%d;%dR", row, col) != 2) {
} *row = 24;
*col = 80;
} }
fprintf(stderr, ESC "8"); /*
tcsetattr(STDERR_FILENO, TCSANOW, &saved); * Restore above saved cursor pos+attr
#endif */
fprintf(stderr, "\e8");
if (screen_cols > 132) /* Restore terminal */
screen_cols = 132; tcsetattr(STDERR_FILENO, TCSANOW, &saved);
return;
#else
*row = 24;
*col = 80;
#endif
} }
int screen_width(void) void screen_init(void)
{ {
screen_init(); initscr(&screen_rows, &screen_cols);
if (screen_cols < 1)
return 80;
return screen_cols;
} }
/** /**