File: tty.c

package info (click to toggle)
hunt 1.5-3
  • links: PTS
  • area: main
  • in suites: woody
  • size: 472 kB
  • ctags: 958
  • sloc: ansic: 10,245; makefile: 84; sh: 14
file content (97 lines) | stat: -rw-r--r-- 2,142 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
 *
 *	This is free software. You can redistribute it and/or modify under
 *	the terms of the GNU General Public License version 2.
 *
 * 	Copyright (C) 1998 by kra
 *
 */
#include "hunt.h"
#include <termios.h>
#include <unistd.h>
#include <stdio.h>

static struct termios	save_termios;
static int		ttysavefd = -1;
static enum { RESET, RAW, CBREAK }	ttystate = RESET;

/* put terminal into a cbreak mode */
int tty_cbreak(int fd, int wait_for_chars, int timer_dsec)
{
	struct termios	buf;

	if (tcgetattr(fd, &save_termios) < 0)
		return -1;
	buf = save_termios;
	buf.c_lflag &= ~(ECHO | ICANON); /* echo off, canonical mode off */

	buf.c_cc[VMIN] = wait_for_chars;
	buf.c_cc[VTIME] = timer_dsec;

	if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
		return -1;
	ttystate = CBREAK;
	ttysavefd = fd;
	return 0;
}

/* put terminal into a raw mode */
int tty_raw(int fd, int wait_for_chars, int timer_dsec)
{
	struct termios	buf;

	if (tcgetattr(fd, &save_termios) < 0)
		return -1;

	buf = save_termios;

	buf.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG);
					/* echo off, canonical mode off, extended input
					   processing off, signal chars off */
	buf.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
					/* no SIGINT on BREAK, CR-to-NL off, input parity
					   check off, don't strip 8th bit on input,
					   output flow control off */
	buf.c_cflag &= ~(CSIZE | PARENB);
					/* clear size bits, parity checking off */
	buf.c_cflag |= CS8;
					/* set 8 bits/char */

	buf.c_oflag &= ~(OPOST);
					/* output processing off */

	buf.c_cc[VMIN] = wait_for_chars;
	buf.c_cc[VTIME] = timer_dsec;
	if (tcsetattr(fd, TCSAFLUSH, &buf) < 0)
		return -1;
	ttystate = RAW;
	ttysavefd = fd;
	return 0;
}

/* restore terminal's mode */
int tty_reset(int fd)
{
	if (ttystate != CBREAK && ttystate != RAW)
		return 0;

	if (tcsetattr(fd, TCSAFLUSH, &save_termios) < 0)
		return -1;
	ttystate = RESET;
	return(0);
}

/* can be set up by atexit(tty_atexit) */
void tty_atexit(void)
{
	if (ttysavefd >= 0 && ttystate != RESET)
		tty_reset(ttysavefd);
}

/* reset linux terminal */
void tty_tput_reset(void)
{
	printf("\033c\033]R");
	fflush(stdout);
}