change ct_term internal interface

This commit is contained in:
Emile Clark-Boman 2025-09-28 00:06:40 +10:00
parent 17d763c597
commit 866fd14b51
3 changed files with 50 additions and 34 deletions

8
src/ct_alloc.h Normal file
View file

@ -0,0 +1,8 @@
#ifndef CURSETREE_ALLOC_H
#define CURSETREE_ALLOC_H
#include <stdlib.h>
#define CT_ALLOC(type, count) ((type *)malloc(sizeof(type) * count))
#endif /* CURSETREE_ALLOC_H */

View file

@ -1,32 +1,39 @@
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "_ct_shared.h"
#include "ct_alloc.h"
#include "term.h"
int stashterm(struct ct_term **const term) {
struct ct_term *t = (struct ct_term *)malloc(sizeof(struct ct_term));
static inline int ct_tty(struct termios *restrict const termios) {
int fd = open("/dev/tty", O_RDONLY);
t->fd = open("/dev/tty", O_RDONLY);
if (t->fd == -1)
goto fail;
else if (tcgetattr(t->fd, &t->termios0) == -1) {
close(t->fd);
goto fail;
if (fd != -1 && tcgetattr(fd, termios) == -1) {
close(fd);
return -2;
}
t->termios = t->termios0;
*term = t;
return OK;
fail:
free(t);
return ERR;
end:
return fd;
}
void resetterm(struct ct_term *const term) {
int ct_stashterm(struct ct_term **restrict term) {
struct ct_term *t = (struct ct_term *)malloc(sizeof(struct ct_term));
// cast away the const to initialise these fields
*(int *)&(*term)->fd = ct_tty((struct termios *)&(*term)->termios0);
if ((*term)->fd < 0) {
free(*term);
return NERR;
}
// duplicate as termios0 will now be readonly
(*term)->termios = (*term)->termios0;
ct_termsize(*term);
return OK;
}
void ct_resetterm(struct ct_term *const term) {
if (term->fd != -1) {
close(term->fd);
/* WARNING: should tcsetattr instead be called on term->fd before closing?
@ -36,12 +43,3 @@ void resetterm(struct ct_term *const term) {
free(term);
}
int termsize(struct ct_term *const term) {
struct winsize argp;
if (ioctl(term->fd, TIOCGWINSZ, &argp) == -1)
return ERR;
term->rows = argp.ws_row;
term->cols = argp.ws_col;
return OK;
}

View file

@ -2,20 +2,30 @@
#define _CURSETREE_TERM_H
#include <termios.h>
#include <sys/ioctl.h>
#include "_ct_shared.h"
#include "ct_shared.h"
struct ct_term {
int fd;
const int fd;
pos cols;
pos rows;
struct termios termios0;
struct termios termios;
const struct termios termios0;
};
int stashterm(struct ct_term **const term);
void resetterm(struct ct_term *const term);
int termsize(struct ct_term *const term);
static inline int ct_termsize(struct ct_term *const term) {
struct winsize argp;
if (ioctl(term->fd, TIOCGWINSZ, &argp) == -1)
return ERR;
term->rows = argp.ws_row;
term->cols = argp.ws_col;
return OK;
}
int ct_stashterm(struct ct_term **const term);
void ct_resetterm(struct ct_term *const term);
#endif /* _CURSETREE_TERM_H */