util: Import screen_width() developed for the SMCRoute project

This patch introduces the screen_width() method from the SMCRoute
project.  The code is hereby also available under MIT/X11.

Signed-off-by: Joachim Nilsson <troglobit@gmail.com>
This commit is contained in:
Joachim Nilsson
2017-07-04 12:53:19 +02:00
parent 9bcb3e5778
commit 90793c71a2
2 changed files with 42 additions and 4 deletions
+37
View File
@@ -21,10 +21,17 @@
* THE SOFTWARE.
*/
#include "config.h"
#include <ctype.h> /* isprint() */
#include <string.h>
#include <unistd.h>
#ifdef HAVE_TERMIOS_H /* for screen_width() */
#include <poll.h>
#include <stdio.h>
#include <termios.h>
#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
+5 -4
View File
@@ -1,6 +1,6 @@
/* Misc. shared utility functions for initctl, reboot and finit
*
* Copyright (c) 2016 Joachim Nilsson <troglobit@gmail.com>
* Copyright (c) 2016-2017 Joachim Nilsson <troglobit@gmail.com>
*
* 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_ */