refactor ct_term

This commit is contained in:
Emile Clark-Boman 2025-09-24 16:56:09 +10:00
parent 08e4376a35
commit 7f4f9941de
2 changed files with 27 additions and 14 deletions

View file

@ -1,23 +1,36 @@
#include <fcntl.h> #include <fcntl.h>
#include <sys/ioctl.h>
#include <stdlib.h> #include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h> #include <unistd.h>
#include "_ct_shared.h"
#include "term.h" #include "term.h"
int getterm(struct ct_term *const term) { int stashterm(const struct ct_term **const term) {
if ((term->fd = open("/dev/tty", O_RDONLY)) == -1) struct ct_term *t = (struct ct_term *)malloc(sizeof(struct ct_term));
return 1;
if (tcgetattr(term->fd, &term->termios0) == -1) t->fd = open("/dev/tty", O_RDONLY);
return 1; if (t->fd == -1)
term->termios = term->termios0; goto fail;
return 0; else if (tcgetattr(t->fd, &t->termios0) == -1) {
close(t->fd);
goto fail;
}
t->termios = t->termios0;
*term = t;
return OK;
fail:
free(t);
return ERR;
} }
void endterm(struct ct_term *const term) { void resetterm(struct ct_term *const term) {
if (term->fd != -1) { if (term->fd != -1) {
close(term->fd); close(term->fd);
/* WARNING: should tcsetattr instead be called on term->fd before closing? */ /* WARNING: should tcsetattr instead be called on term->fd before closing?
*/
tcsetattr(STDIN_FILENO, TCSANOW, &term->termios0); tcsetattr(STDIN_FILENO, TCSANOW, &term->termios0);
} }
free(term); free(term);
@ -26,9 +39,9 @@ void endterm(struct ct_term *const term) {
int termsize(struct ct_term *const term) { int termsize(struct ct_term *const term) {
struct winsize argp; struct winsize argp;
if (ioctl(term->fd, TIOCGWINSZ, &argp) == -1) if (ioctl(term->fd, TIOCGWINSZ, &argp) == -1)
return 1; return ERR;
term->rows = argp.ws_row; term->rows = argp.ws_row;
term->cols = argp.ws_col; term->cols = argp.ws_col;
return 0; return OK;
} }

View file

@ -12,8 +12,8 @@ struct ct_term {
struct termios termios; struct termios termios;
}; };
int getterm(struct ct_term *const term); int stashterm(const struct ct_term **const term);
void endterm(struct ct_term *const term); void resetterm(struct ct_term *const term);
int termsize(struct ct_term *const term); int termsize(struct ct_term *const term);
#endif /* _CURSETREE_TERM_H */ #endif /* _CURSETREE_TERM_H */