From 853cb79cc31a765fa763109d3631e3b96825288b Mon Sep 17 00:00:00 2001 From: Ian Moffett Date: Fri, 21 Feb 2025 22:52:59 -0500 Subject: Smoothen input handling, prevent overlapping text Signed-off-by: Ian Moffett --- src/client/client.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 54 insertions(+), 8 deletions(-) diff --git a/src/client/client.c b/src/client/client.c index f8d3b9a..732cae1 100644 --- a/src/client/client.c +++ b/src/client/client.c @@ -34,6 +34,7 @@ #include #include #include +#include // #define CENTRAL_SERVER "127.0.0.1" #define CENTRAL_SERVER "149.248.6.149" @@ -41,7 +42,29 @@ static struct ostp_session s; static pthread_t td; static volatile int got_thread = 0; +static char input[512]; +static size_t input_i = 0; +static struct termios orig_termios; +static void +enable_raw_mode(void) +{ + struct termios raw; + + tcgetattr(STDIN_FILENO, &orig_termios); + raw = orig_termios; + raw.c_lflag &= ~(ICANON | ECHO); + tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); + + raw.c_lflag &= ~(ECHO | ICANON | ISIG); + raw.c_cflag |= (CS8); +} + +static void +disable_raw_mode(void) +{ + tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); +} static void * recv_td(void *args) { @@ -53,7 +76,7 @@ recv_td(void *args) printf("session_recv() failure\n"); return NULL; } - printf("%s\n>> ", buf); + printf("\n\033[1F\033[2K%s\n>> %s", buf, input); fflush(stdout); } } @@ -72,11 +95,11 @@ sighandle(int dmmy) int main(int argc, char **argv) { - int c, error; - char input[2048]; - char send_buf[2048]; + int error; + char c, send_buf[2048]; size_t len; + tcgetattr(STDIN_FILENO, &orig_termios); setbuf(stdin, NULL); setbuf(stdout, NULL); signal(SIGINT, sighandle); @@ -92,17 +115,40 @@ main(int argc, char **argv) return error; } + atexit(disable_raw_mode); + enable_raw_mode(); + while (1) { printf(">> "); - fflush(stdout); - if (fgets(input, sizeof(input), stdin) == NULL) { - printf("\n"); - continue; + while (read(STDIN_FILENO, &c, 1)) { + if (c == 0x7F && input_i == 0) { + continue; + } else if (c == 0x7F && input_i > 0) { + input[input_i--] = '\0'; + printf("\b ", input_i); + continue; + } + + /* Stop reading if newline */ + if (c == '\n') { + input_i = 0; + printf("\n"); + break; + } + + if (input_i >= sizeof(input)) { + continue; + } + + input[input_i++] = c; + input[input_i] = '\0'; + printf("%c", c); } input[strcspn(input, "\n")] = '\0'; snprintf(send_buf, sizeof(send_buf), "%s: %s", s.username, input); + input[0] = '\0'; session_send(send_buf, strlen(send_buf) + 1, &s); } -- cgit v1.2.3