Files
bluelib/term/sys/linux/print.c

66 lines
1.1 KiB
C

#include <stdio.h>
#include <string.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
int z__b_stream_is_tty(FILE *fp)
{
return isatty(fileno(fp));
}
int z__b_stream_dimensions(FILE *fp, unsigned int *w, unsigned int *h)
{
if (!isatty(fileno(fp))) {
return -1;
}
struct winsize ws;
if (ioctl(fileno(fp), TIOCGWINSZ, &ws) == -1) {
return -1;
}
if (w) {
*w = ws.ws_col;
}
if (h) {
*h = ws.ws_row;
}
return 0;
}
int z__b_stream_cursorpos(FILE *in, FILE *out, unsigned int *x, unsigned int *y)
{
if (!isatty(fileno(in)) || !isatty(fileno(out))) {
return -1;
}
struct termios term, restore;
tcgetattr(fileno(in), &term);
tcgetattr(fileno(in), &restore);
term.c_lflag &= ~(ICANON | ECHO);
tcsetattr(fileno(in), TCSANOW, &term);
const char *cmd = "\033[6n";
write(fileno(out), cmd, strlen(cmd));
char buf[64];
read(fileno(in), buf, sizeof buf);
tcsetattr(fileno(in), TCSANOW, &restore);
unsigned int row, col;
int r = sscanf(buf, "\033[%u;%uR", &row, &col);
if (r != 2) {
return -1;
}
*x = col - 1;
*y = row - 1;
return 0;
}