cmdline: add internal wrappers for terminal handling

Add functions that set up, save, and restore terminal parameters.
Use existing code as Unix implementation.

Signed-off-by: Dmitry Kozlyuk <dmitry.kozliuk@gmail.com>
Acked-by: Olivier Matz <olivier.matz@6wind.com>
This commit is contained in:
Dmitry Kozlyuk 2020-09-29 00:50:47 +03:00 committed by Thomas Monjalon
parent 51fcb6a1fe
commit 7b5f4e1d30
5 changed files with 52 additions and 12 deletions

View File

@ -0,0 +1,27 @@
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2020 Dmitry Kozlyuk
*/
#include <string.h>
#include "cmdline_private.h"
void
terminal_adjust(struct cmdline *cl)
{
struct termios term;
tcgetattr(0, &cl->oldterm);
memcpy(&term, &cl->oldterm, sizeof(term));
term.c_lflag &= ~(ICANON | ECHO | ISIG);
tcsetattr(0, TCSANOW, &term);
setbuf(stdin, NULL);
}
void
terminal_restore(const struct cmdline *cl)
{
tcsetattr(fileno(stdin), TCSANOW, &cl->oldterm);
}

View File

@ -0,0 +1,16 @@
/* SPDX-License-Identifier: BSD-3-Clause
* Copyright (c) 2020 Dmitry Kozlyuk
*/
#ifndef _CMDLINE_PRIVATE_H_
#define _CMDLINE_PRIVATE_H_
#include <cmdline.h>
/* Disable buffering and echoing, save previous settings to oldterm. */
void terminal_adjust(struct cmdline *cl);
/* Restore terminal settings form oldterm. */
void terminal_restore(const struct cmdline *cl);
#endif

View File

@ -13,6 +13,7 @@
#include <fcntl.h> #include <fcntl.h>
#include "cmdline.h" #include "cmdline.h"
#include "cmdline_private.h"
#include "cmdline_socket.h" #include "cmdline_socket.h"
struct cmdline * struct cmdline *
@ -36,18 +37,11 @@ struct cmdline *
cmdline_stdin_new(cmdline_parse_ctx_t *ctx, const char *prompt) cmdline_stdin_new(cmdline_parse_ctx_t *ctx, const char *prompt)
{ {
struct cmdline *cl; struct cmdline *cl;
struct termios oldterm, term;
tcgetattr(0, &oldterm);
memcpy(&term, &oldterm, sizeof(term));
term.c_lflag &= ~(ICANON | ECHO | ISIG);
tcsetattr(0, TCSANOW, &term);
setbuf(stdin, NULL);
cl = cmdline_new(ctx, prompt, 0, 1); cl = cmdline_new(ctx, prompt, 0, 1);
if (cl) if (cl != NULL)
memcpy(&cl->oldterm, &oldterm, sizeof(term)); terminal_adjust(cl);
return cl; return cl;
} }
@ -55,8 +49,8 @@ cmdline_stdin_new(cmdline_parse_ctx_t *ctx, const char *prompt)
void void
cmdline_stdin_exit(struct cmdline *cl) cmdline_stdin_exit(struct cmdline *cl)
{ {
if (!cl) if (cl == NULL)
return; return;
tcsetattr(fileno(stdin), TCSANOW, &cl->oldterm); terminal_restore(cl);
} }

View File

@ -10,7 +10,6 @@
#include <string.h> #include <string.h>
#include <stdarg.h> #include <stdarg.h>
#include <ctype.h> #include <ctype.h>
#include <termios.h>
#include "cmdline_vt100.h" #include "cmdline_vt100.h"

View File

@ -25,4 +25,8 @@ headers = files('cmdline.h',
'cmdline_cirbuf.h', 'cmdline_cirbuf.h',
'cmdline_parse_portlist.h') 'cmdline_parse_portlist.h')
if not is_windows
sources += files('cmdline_os_unix.c')
endif
deps += ['net'] deps += ['net']