xref: /openbsd-src/usr.bin/less/ttyin.c (revision d65139b4ae439ce0363945a0003c48c6286cc117)
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 int utf_mode;
20 
21 /*
22  * Open keyboard for input.
23  */
24 void
open_getchr(void)25 open_getchr(void)
26 {
27 	/*
28 	 * Try /dev/tty.
29 	 * If that doesn't work, use file descriptor 2,
30 	 * which in Unix is usually attached to the screen,
31 	 * but also usually lets you read from the keyboard.
32 	 */
33 	tty = open("/dev/tty", O_RDONLY);
34 	if (tty == -1)
35 		tty = STDERR_FILENO;
36 }
37 
38 /*
39  * Get a character from the keyboard.
40  */
41 int
getchr(void)42 getchr(void)
43 {
44 	unsigned char c;
45 	int result;
46 
47 	do {
48 		result = iread(tty, &c, sizeof (char));
49 		if (result == READ_INTR)
50 			return (READ_INTR);
51 		if (result < 0) {
52 			/*
53 			 * Don't call error() here,
54 			 * because error calls getchr!
55 			 */
56 			quit(QUIT_ERROR);
57 		}
58 		/*
59 		 * Various parts of the program cannot handle
60 		 * an input character of '\0'.
61 		 * If a '\0' was actually typed, convert it to '\340' here.
62 		 */
63 		if (c == '\0')
64 			c = 0340;
65 	} while (result != 1);
66 
67 	return (c & 0xFF);
68 }
69