From 5868cfb8c3031948b2f60a88d7887c3c2d981920 Mon Sep 17 00:00:00 2001 From: Luxferre Date: Sun, 21 Aug 2022 10:50:45 +0300 Subject: [PATCH] A better terminal handling --- equi.c | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/equi.c b/equi.c index c75bea0..08bd4f6 100644 --- a/equi.c +++ b/equi.c @@ -733,14 +733,21 @@ void equi_main_loop() { ram.ibp = 65535U; } +#if !defined __CC65__ +struct termios tty_opts_raw, tty_opts_backup; +void restore_term() { + /* restore the terminal settings */ + tcsetattr(STDIN_FILENO, TCSANOW, &tty_opts_backup); +} +#endif + /* Equi VM entry point */ int main(int argc, char* argv[]) { uchar instr, bc, modec, smode = 0; FILE *prog = stdin; /* _attempt_ to disable buffering for char input/output */ #if !defined __CC65__ - struct termios tty_opts_raw, tty_opts_backup; - tcgetattr(STDIN_FILENO, &tty_opts_backup); + atexit(&restore_term); cfmakeraw(&tty_opts_raw); tcsetattr(STDIN_FILENO, TCSANOW, &tty_opts_raw); #endif @@ -764,7 +771,6 @@ int main(int argc, char* argv[]) { else if(argv[2][0] == 's') /* enter silent mode, don't print the banners and prompts */ smode = 1; } - /* Start input buffering from the start of command buffer (-1 because we use prefix increment) */ ram.ibp = 65535U; if(!ram.MM && !smode) { /* skip the terminal init and the greeting if in minification or silent mode */ @@ -777,7 +783,6 @@ int main(int argc, char* argv[]) { #endif printf("Welcome to Equi v" EQUI_VER " by Luxferre, 2022" CRLF "System RAM: %d bytes" CRLF "Equi ready" CRLF CRLF "> ", (int) sizeof(ram)); } - while(1) { /* Now, we're in the command mode loop */ instr = fgetc(prog); /* Fetch the next instruction from the keyboard/file */ if(instr == 0xFFU || instr == 0U || instr == 3U || instr == 4U) /* exit on zero byte or ctrl+C or ctrl+D */ @@ -839,10 +844,6 @@ int main(int argc, char* argv[]) { cputc(instr); /* echo it if not in silent mode */ } } /* command mode loop end */ -#ifndef __CC65__ - /* restore the terminal settings */ - tcsetattr(STDIN_FILENO, TCSANOW, &tty_opts_backup); -#endif fclose(prog); /* close the input file */ return 0; }