1 /* terminal.c - prepare the terminal
2 *
3 * Copyright (C) 2000 Jochen Voss. */
4
5 static const char rcsid[] = "$Id: terminal.c 4839 2003-04-13 16:50:02Z voss $";
6
7 #ifdef HAVE_CONFIG_H
8 # include <config.h>
9 #endif
10
11 #ifdef _XOPEN_SOURCE
12 #define _XOPEN_SOURCE_EXTENDED 1
13 #endif
14
15 #include <string.h>
16 #include <unistd.h>
17 #include <sys/stat.h>
18 #if HAVE_ERRNO_H
19 #include <errno.h>
20 #else
21 extern int errno;
22 #endif
23 #if HAVE_TERMIOS_H
24 #include <termios.h>
25 #endif
26 #include <assert.h>
27
28 #include "moon-buggy.h"
29
30
31 static mode_t term_mode; /* The terminal mode before we changed it */
32 static int term_mode_valid; /* true iff the above is valid */
33 static int attributes_changed; /* true iff we changed the IXON attribute */
34
35
36 void
term_prepare(int mesg_n_flag)37 term_prepare (int mesg_n_flag)
38 /* Prepare the terminal for game play.
39 * This tries to disable the C-s key and, if MESG_N_FLAG is set,
40 * restricts write access to the terminal as "mesg n" would do. */
41 {
42 struct stat st;
43 #if HAVE_TERMIOS_H
44 struct termios settings;
45 #endif
46 int res;
47
48 assert (! term_mode_valid);
49 if ( ! isatty (0) ) return;
50
51 if (mesg_n_flag) {
52 res = fstat (0, &st);
53 if (res < 0)
54 fatal ("Cannot get terminal attributes: %s", strerror (errno));
55
56 term_mode = st.st_mode;
57 term_mode_valid = 1;
58
59 st.st_mode &= ~(S_IWGRP|S_IWOTH);
60 res = fchmod (0, st.st_mode);
61 if (res < 0)
62 fatal ("Cannot set terminal permissions: %s", strerror (errno));
63 }
64
65 #if HAVE_TERMIOS_H
66 res = tcgetattr (0, &settings);
67 if (res < 0)
68 fatal ("Cannot get terminal attributes: %s", strerror (errno));
69
70 if (settings.c_iflag & IXON) {
71 settings.c_iflag &= ~IXON;
72 res = tcsetattr (0, TCSANOW, &settings);
73 if (res < 0)
74 fatal ("Cannot set terminal attributes: %s", strerror (errno));
75 attributes_changed = 1;
76 }
77 #endif
78 }
79
80 void
term_restore(void)81 term_restore (void)
82 /* Restore the terminal's original access mode. */
83 {
84 #if HAVE_TERMIOS_H
85 struct termios settings;
86 #endif
87 int res;
88
89 #if HAVE_TERMIOS_H
90 if (attributes_changed) {
91 res = tcgetattr (0, &settings);
92 if (res < 0)
93 fatal ("Cannot get terminal attributes: %s", strerror (errno));
94
95 settings.c_iflag |= IXON;
96 res = tcsetattr (0, TCSANOW, &settings);
97 if (res < 0)
98 fatal ("Cannot set terminal attributes: %s", strerror (errno));
99 }
100 #endif
101
102 if (term_mode_valid) {
103 res = fchmod (0, term_mode);
104 if (res < 0)
105 fatal ("Cannot restore terminal permissions: %s", strerror (errno));
106 term_mode_valid = 0;
107 }
108 }
109