From bcfcbaf529eb723d9466612985a448dffc3dbe81 Mon Sep 17 00:00:00 2001 From: Emile Clark-Boman Date: Wed, 24 Sep 2025 15:46:56 +1000 Subject: [PATCH] add struct ct_term terminfo/termios/ioctl wrapper --- src/term.c | 34 ++++++++++++++++++++++++++++++++++ src/term.h | 19 +++++++++++++++++++ src/test.c | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 89 insertions(+) create mode 100644 src/term.c create mode 100644 src/term.h create mode 100644 src/test.c diff --git a/src/term.c b/src/term.c new file mode 100644 index 0000000..6b184a2 --- /dev/null +++ b/src/term.c @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +#include "term.h" + +int getterm(struct ct_term *const term) { + if ((term->fd = open("/dev/tty", O_RDONLY)) == -1) + return 1; + if (tcgetattr(term->fd, &term->termios0) == -1) + return 1; + term->termios = term->termios0; + return 0; +} + +void endterm(struct ct_term *const term) { + if (term->fd != -1) { + close(term->fd); + /* WARNING: should tcsetattr instead be called on term->fd before closing? */ + tcsetattr(STDIN_FILENO, TCSANOW, &term->termios0); + } + free(term); +} + +int termsize(struct ct_term *const term) { + struct winsize argp; + if (ioctl(term->fd, TIOCGWINSZ, &argp) == -1) + return 1; + + term->rows = argp.ws_row; + term->cols = argp.ws_col; + return 0; +} diff --git a/src/term.h b/src/term.h new file mode 100644 index 0000000..ba6c417 --- /dev/null +++ b/src/term.h @@ -0,0 +1,19 @@ +#ifndef _CURSETREE_TERM_H +#define _CURSETREE_TERM_H + +#include "termios.h" + +struct ct_term { + int fd; + unsigned short cols; + unsigned short rows; + + struct termios termios0; + struct termios termios; +}; + +int getterm(struct ct_term *const term); +void endterm(struct ct_term *const term); +int termsize(struct ct_term *const term); + +#endif /* _CURSETREE_TERM_H */ diff --git a/src/test.c b/src/test.c new file mode 100644 index 0000000..a35b786 --- /dev/null +++ b/src/test.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include + +#include "term.h" + +int main(void) { + struct ct_term *const term = (struct ct_term *)malloc(sizeof(struct ct_term)); + if (getterm(term)) { + perror("getterm"); + endterm(term); + exit(1); + } + + if (termsize(term)) { + perror("termsize"); + endterm(term); + exit(1); + } + + + printf("\e[2J\e[1;1H"); + + char *line = (char *)malloc(sizeof(char) * (term->cols + 1)); + memset(line, 'X', term->cols); + line[term->cols] = '\0'; + + for (int i=0; i < term->rows; i++) { + printf("%s", line); + } + sleep(3); + + endterm(term); + return 0; +}