add struct ct_term terminfo/termios/ioctl wrapper

This commit is contained in:
Emile Clark-Boman 2025-09-24 15:46:56 +10:00
parent 2033721c22
commit bcfcbaf529
3 changed files with 89 additions and 0 deletions

34
src/term.c Normal file
View file

@ -0,0 +1,34 @@
#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <unistd.h>
#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;
}

19
src/term.h Normal file
View file

@ -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 */

36
src/test.c Normal file
View file

@ -0,0 +1,36 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#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;
}