libite 2.6.1
conio.c
Go to the documentation of this file.
1/* A conio.h like implementation for VTANSI displays.
2 *
3 * Copyright (c) 2009-2021 Joachim Wiberg <troglobit@gmail.com>
4 *
5 * Permission to use, copy, modify, and/or distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
8 *
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16 */
17
24
25#include <poll.h>
26#include <stdio.h>
27#include <termios.h>
28#include <unistd.h>
29
44void initscr(int *row, int *col)
45{
46 if (!row || !col)
47 return;
48
49#if defined(TCSANOW) && defined(POLLIN)
50 struct termios tc, saved;
51 struct pollfd fd = { STDIN_FILENO, POLLIN, 0 };
52
53 if (!isatty(STDIN_FILENO) || !isatty(STDOUT_FILENO)) {
54 *row = 24;
55 *col = 80;
56 return;
57 }
58
59 /* Disable echo to terminal while probing */
60 tcgetattr(STDOUT_FILENO, &tc);
61 saved = tc;
62 tc.c_cflag |= (CLOCAL | CREAD);
63 tc.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
64 tcsetattr(STDOUT_FILENO, TCSANOW, &tc);
65
66 /*
67 * Save cursor pos+attr
68 * Diable top+bottom margins
69 * Set cursor at the far bottom,right pos
70 * Query term for resulting pos
71 */
72 fprintf(stdout, "\e7" "\e[r" "\e[999;999H" "\e[6n");
73 fflush(stdout);
74
75 /*
76 * Wait here for terminal to echo back \e[row,lineR ...
77 */
78 if (poll(&fd, 1, 300) <= 0 || scanf("\e[%d;%dR", row, col) != 2) {
79 *row = 24;
80 *col = 80;
81 }
82
83 /*
84 * Restore above saved cursor pos+attr
85 */
86 fprintf(stdout, "\e8");
87 fflush(stdout);
88
89 /* Restore terminal */
90 tcsetattr(STDOUT_FILENO, TCSANOW, &saved);
91
92 return;
93#else
94 *row = 24;
95 *col = 80;
96#endif
97}
98
void initscr(int *row, int *col)
Definition conio.c:44