xref: /openbsd-src/usr.bin/less/ttyin.c (revision ae3cb403620ab940fbaabb3055fac045a63d56b7)
1 /*
2  * Copyright (C) 1984-2012  Mark Nudelman
3  * Modified for use with illumos by Garrett D'Amore.
4  * Copyright 2014 Garrett D'Amore <garrett@damore.org>
5  *
6  * You may distribute under the terms of either the GNU General Public
7  * License or the Less License, as specified in the README file.
8  *
9  * For more information, see the README file.
10  */
11 
12 /*
13  * Routines dealing with getting input from the keyboard (i.e. from the user).
14  */
15 
16 #include "less.h"
17 
18 int tty;
19 extern volatile sig_atomic_t sigs;
20 extern int utf_mode;
21 
22 /*
23  * Open keyboard for input.
24  */
25 void
26 open_getchr(void)
27 {
28 	/*
29 	 * Try /dev/tty.
30 	 * If that doesn't work, use file descriptor 2,
31 	 * which in Unix is usually attached to the screen,
32 	 * but also usually lets you read from the keyboard.
33 	 */
34 	tty = open("/dev/tty", O_RDONLY);
35 	if (tty < 0)
36 		tty = STDERR_FILENO;
37 }
38 
39 /*
40  * Get a character from the keyboard.
41  */
42 int
43 getchr(void)
44 {
45 	unsigned char c;
46 	int result;
47 
48 	do {
49 		result = iread(tty, &c, sizeof (char));
50 		if (result == READ_INTR)
51 			return (READ_INTR);
52 		if (result < 0) {
53 			/*
54 			 * Don't call error() here,
55 			 * because error calls getchr!
56 			 */
57 			quit(QUIT_ERROR);
58 		}
59 		/*
60 		 * Various parts of the program cannot handle
61 		 * an input character of '\0'.
62 		 * If a '\0' was actually typed, convert it to '\340' here.
63 		 */
64 		if (c == '\0')
65 			c = 0340;
66 	} while (result != 1);
67 
68 	return (c & 0xFF);
69 }
70