Debian Codegraph @

code/sys/con_tty.c

raw symbols SCIP
1 /*
2 ===========================================================================
3 Copyright (C) 1999-2005 Id Software, Inc.
4
5 This file is part of Quake III Arena source code.
6
7 Quake III Arena source code is free software; you can redistribute it
8 and/or modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of the License,
10 or (at your option) any later version.
11
12 Quake III Arena source code is distributed in the hope that it will be
13 useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Quake III Arena source code; if not, write to the Free Software
19 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 ===========================================================================
21 */
22
23 #include "../qcommon/q_shared.h"
24 #include "../qcommon/qcommon.h"
25 #include "sys_local.h"
26
27 #ifndef DEDICATED
28 #include "../client/client.h"
29 #endif
30
31 #include <unistd.h>
32 #include <signal.h>
33 #include <termios.h>
34 #include <fcntl.h>
35 #include <sys/time.h>
36
37 /*
38 =============================================================
39 tty console routines
40
41 NOTE: if the user is editing a line when something gets printed to the early
42 console then it won't look good so we provide CON_Hide and CON_Show to be
43 called before and after a stdout or stderr output
44 =============================================================
45 */
46
47 extern qboolean stdinIsATTY;
48 static qboolean stdin_active;
49 // general flag to tell about tty console mode
50 static qboolean ttycon_on = qfalse;
51 static int ttycon_hide = 0;
52 static int ttycon_show_overdue = 0;
53
54 // some key codes that the terminal may be using, initialised on start up
55 static int TTY_erase;
56 static int TTY_eof;
57
58 static struct termios TTY_tc;
59
60 static field_t TTY_con;
61
62 // This is somewhat of aduplicate of the graphical console history
63 // but it's safer more modular to have our own here
64 #define CON_HISTORY 32
65 static field_t ttyEditLines[ CON_HISTORY ];
66 static int hist_current = -1, hist_count = 0;
67
68 #ifndef DEDICATED
69 // Don't use "]" as it would be the same as in-game console,
70 // this makes it clear where input came from.
71 #define TTY_CONSOLE_PROMPT "tty]"
72 #else
73 #define TTY_CONSOLE_PROMPT "]"
74 #endif
75
76 /*
77 ==================
78 CON_Back
79
80 Output a backspace
81
82 NOTE: it seems on some terminals just sending '\b' is not enough so instead we
83 send "\b \b"
84 (FIXME there may be a way to find out if '\b' alone would work though)
85 ==================
86 */
87 static void CON_Back( void )
88 {
89 char key;
90 size_t Q_UNUSED_VAR size;
91
92 key = '\b';
93 size = write(STDOUT_FILENO, &key, 1);
94 key = ' ';
95 size = write(STDOUT_FILENO, &key, 1);
96 key = '\b';
97 size = write(STDOUT_FILENO, &key, 1);
98 }
99
100 /*
101 ==================
102 CON_Hide
103
104 Clear the display of the line currently edited
105 bring cursor back to beginning of line
106 ==================
107 */
108 static void CON_Hide( void )
109 {
110 if( ttycon_on )
111 {
112 int i;
113 if (ttycon_hide)
114 {
115 ttycon_hide++;
116 return;
117 }
118 if (TTY_con.cursor>0)
119 {
120 for (i=0; i<TTY_con.cursor; i++)
121 {
122 CON_Back();
123 }
124 }
125 // Delete prompt
126 for (i = strlen(TTY_CONSOLE_PROMPT); i > 0; i--) {
127 CON_Back();
128 }
129 ttycon_hide++;
130 }
131 }
132
133 /*
134 ==================
135 CON_Show
136
137 Show the current line
138 FIXME need to position the cursor if needed?
139 ==================
140 */
141 static void CON_Show( void )
142 {
143 if( ttycon_on )
144 {
145 int i;
146
147 assert(ttycon_hide>0);
148 ttycon_hide--;
149 if (ttycon_hide == 0)
150 {
151 size_t Q_UNUSED_VAR size;
152 size = write(STDOUT_FILENO, TTY_CONSOLE_PROMPT, strlen(TTY_CONSOLE_PROMPT));
153 if (TTY_con.cursor)
154 {
155 for (i=0; i<TTY_con.cursor; i++)
156 {
157 size = write(STDOUT_FILENO, TTY_con.buffer+i, 1);
158 }
159 }
160 }
161 }
162 }
163
164 /*
165 ==================
166 CON_Shutdown
167
168 Never exit without calling this, or your terminal will be left in a pretty bad state
169 ==================
170 */
171 void CON_Shutdown( void )
172 {
173 if (ttycon_on)
174 {
175 CON_Hide();
176 tcsetattr (STDIN_FILENO, TCSADRAIN, &TTY_tc);
177 }
178
179 // Restore blocking to stdin reads
180 fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) & ~O_NONBLOCK);
181 }
182
183 /*
184 ==================
185 Hist_Add
186 ==================
187 */
188 void Hist_Add(field_t *field)
189 {
190 int i;
191
192 // Don't save blank lines in history.
193 if (!field->cursor)
194 return;
195
196 assert(hist_count <= CON_HISTORY);
197 assert(hist_count >= 0);
198 assert(hist_current >= -1);
199 assert(hist_current <= hist_count);
200 // make some room
201 for (i=CON_HISTORY-1; i>0; i--)
202 {
203 ttyEditLines[i] = ttyEditLines[i-1];
204 }
205 ttyEditLines[0] = *field;
206 if (hist_count<CON_HISTORY)
207 {
208 hist_count++;
209 }
210 hist_current = -1; // re-init
211 }
212
213 /*
214 ==================
215 Hist_Prev
216 ==================
217 */
218 field_t *Hist_Prev( void )
219 {
220 int hist_prev;
221 assert(hist_count <= CON_HISTORY);
222 assert(hist_count >= 0);
223 assert(hist_current >= -1);
224 assert(hist_current <= hist_count);
225 hist_prev = hist_current + 1;
226 if (hist_prev >= hist_count)
227 {
228 return NULL;
229 }
230 hist_current++;
231 return &(ttyEditLines[hist_current]);
232 }
233
234 /*
235 ==================
236 Hist_Next
237 ==================
238 */
239 field_t *Hist_Next( void )
240 {
241 assert(hist_count <= CON_HISTORY);
242 assert(hist_count >= 0);
243 assert(hist_current >= -1);
244 assert(hist_current <= hist_count);
245 if (hist_current >= 0)
246 {
247 hist_current--;
248 }
249 if (hist_current == -1)
250 {
251 return NULL;
252 }
253 return &(ttyEditLines[hist_current]);
254 }
255
256 /*
257 ==================
258 CON_SigCont
259 Reinitialize console input after receiving SIGCONT, as on Linux the terminal seems to lose all
260 set attributes if user did CTRL+Z and then does fg again.
261 ==================
262 */
263
264 void CON_SigCont(int signum)
265 {
266 CON_Init();
267 }
268
269 /*
270 ==================
271 CON_Init
272
273 Initialize the console input (tty mode if possible)
274 ==================
275 */
276 void CON_Init( void )
277 {
278 struct termios tc;
279
280 // If the process is backgrounded (running non interactively)
281 // then SIGTTIN or SIGTOU is emitted, if not caught, turns into a SIGSTP
282 signal(SIGTTIN, SIG_IGN);
283 signal(SIGTTOU, SIG_IGN);
284
285 // If SIGCONT is received, reinitialize console
286 signal(SIGCONT, CON_SigCont);
287
288 // Make stdin reads non-blocking
289 fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL, 0) | O_NONBLOCK );
290
291 if (!stdinIsATTY)
292 {
293 Com_Printf("tty console mode disabled\n");
294 ttycon_on = qfalse;
295 stdin_active = qtrue;
296 return;
297 }
298
299 Field_Clear(&TTY_con);
300 tcgetattr (STDIN_FILENO, &TTY_tc);
301 TTY_erase = TTY_tc.c_cc[VERASE];
302 TTY_eof = TTY_tc.c_cc[VEOF];
303 tc = TTY_tc;
304
305 /*
306 ECHO: don't echo input characters
307 ICANON: enable canonical mode. This enables the special
308 characters EOF, EOL, EOL2, ERASE, KILL, REPRINT,
309 STATUS, and WERASE, and buffers by lines.
310 ISIG: when any of the characters INTR, QUIT, SUSP, or
311 DSUSP are received, generate the corresponding signal
312 */
313 tc.c_lflag &= ~(ECHO | ICANON);
314
315 /*
316 ISTRIP strip off bit 8
317 INPCK enable input parity checking
318 */
319 tc.c_iflag &= ~(ISTRIP | INPCK);
320 tc.c_cc[VMIN] = 1;
321 tc.c_cc[VTIME] = 0;
322 tcsetattr (STDIN_FILENO, TCSADRAIN, &tc);
323 ttycon_on = qtrue;
324 ttycon_hide = 1; // Mark as hidden, so prompt is shown in CON_Show
325 CON_Show();
326 }
327
328 /*
329 ==================
330 CON_Input
331 ==================
332 */
333 char *CON_Input( void )
334 {
335 // we use this when sending back commands
336 static char text[MAX_EDIT_LINE];
337 int avail;
338 char key;
339 field_t *history;
340 size_t Q_UNUSED_VAR size;
341
342 if(ttycon_on)
343 {
344 avail = read(STDIN_FILENO, &key, 1);
345 if (avail != -1)
346 {
347 // we have something
348 // backspace?
349 // NOTE TTimo testing a lot of values .. seems it's the only way to get it to work everywhere
350 if ((key == TTY_erase) || (key == 127) || (key == 8))
351 {
352 if (TTY_con.cursor > 0)
353 {
354 TTY_con.cursor--;
355 TTY_con.buffer[TTY_con.cursor] = '\0';
356 CON_Back();
357 }
358 return NULL;
359 }
360 // check if this is a control char
361 if ((key) && (key) < ' ')
362 {
363 if (key == '\n')
364 {
365 #ifndef DEDICATED
366 // if not in the game explicitly prepend a slash if needed
367 if (clc.state != CA_ACTIVE && con_autochat->integer && TTY_con.cursor &&
368 TTY_con.buffer[0] != '/' && TTY_con.buffer[0] != '\\')
369 {
370 memmove(TTY_con.buffer + 1, TTY_con.buffer, sizeof(TTY_con.buffer) - 1);
371 TTY_con.buffer[0] = '\\';
372 TTY_con.cursor++;
373 }
374
375 if (TTY_con.buffer[0] == '/' || TTY_con.buffer[0] == '\\') {
376 Q_strncpyz(text, TTY_con.buffer + 1, sizeof(text));
377 } else if (TTY_con.cursor) {
378 if (con_autochat->integer) {
379 Com_sprintf(text, sizeof(text), "cmd say %s", TTY_con.buffer);
380 } else {
381 Q_strncpyz(text, TTY_con.buffer, sizeof(text));
382 }
383 } else {
384 text[0] = '\0';
385 }
386
387 // push it in history
388 Hist_Add(&TTY_con);
389 CON_Hide();
390 Com_Printf("%s%s\n", TTY_CONSOLE_PROMPT, TTY_con.buffer);
391 Field_Clear(&TTY_con);
392 CON_Show();
393 #else
394 // push it in history
395 Hist_Add(&TTY_con);
396 Q_strncpyz(text, TTY_con.buffer, sizeof(text));
397 Field_Clear(&TTY_con);
398 key = '\n';
399 size = write(STDOUT_FILENO, &key, 1);
400 size = write(STDOUT_FILENO, TTY_CONSOLE_PROMPT, strlen(TTY_CONSOLE_PROMPT));
401 #endif
402 return text;
403 }
404 if (key == '\t')
405 {
406 CON_Hide();
407 Field_AutoComplete( &TTY_con );
408 CON_Show();
409 return NULL;
410 }
411 avail = read(STDIN_FILENO, &key, 1);
412 if (avail != -1)
413 {
414 // VT 100 keys
415 if (key == '[' || key == 'O')
416 {
417 avail = read(STDIN_FILENO, &key, 1);
418 if (avail != -1)
419 {
420 switch (key)
421 {
422 case 'A':
423 history = Hist_Prev();
424 if (history)
425 {
426 CON_Hide();
427 TTY_con = *history;
428 CON_Show();
429 }
430 tcflush(STDIN_FILENO, TCIFLUSH);
431 return NULL;
432 break;
433 case 'B':
434 history = Hist_Next();
435 CON_Hide();
436 if (history)
437 {
438 TTY_con = *history;
439 } else
440 {
441 Field_Clear(&TTY_con);
442 }
443 CON_Show();
444 tcflush(STDIN_FILENO, TCIFLUSH);
445 return NULL;
446 break;
447 case 'C':
448 return NULL;
449 case 'D':
450 return NULL;
451 }
452 }
453 }
454 }
455 Com_DPrintf("droping ISCTL sequence: %d, TTY_erase: %d\n", key, TTY_erase);
456 tcflush(STDIN_FILENO, TCIFLUSH);
457 return NULL;
458 }
459 if (TTY_con.cursor >= sizeof(text) - 1)
460 return NULL;
461 // push regular character
462 TTY_con.buffer[TTY_con.cursor] = key;
463 TTY_con.cursor++; // next char will always be '\0'
464 // print the current line (this is differential)
465 size = write(STDOUT_FILENO, &key, 1);
466 }
467
468 return NULL;
469 }
470 else if (stdin_active)
471 {
472 int len;
473 fd_set fdset;
474 struct timeval timeout;
475
476 FD_ZERO(&fdset);
477 FD_SET(STDIN_FILENO, &fdset); // stdin
478 timeout.tv_sec = 0;
479 timeout.tv_usec = 0;
480 if(select (STDIN_FILENO + 1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(STDIN_FILENO, &fdset))
481 return NULL;
482
483 len = read(STDIN_FILENO, text, sizeof(text));
484 if (len == 0)
485 { // eof!
486 stdin_active = qfalse;
487 return NULL;
488 }
489
490 if (len < 1)
491 return NULL;
492 text[len-1] = 0; // rip off the /n and terminate
493
494 return text;
495 }
496 return NULL;
497 }
498
499 /*
500 ==================
501 CON_Print
502 ==================
503 */
504 void CON_Print( const char *msg )
505 {
506 if (!msg[0])
507 return;
508
509 CON_Hide( );
510
511 if( com_ansiColor && com_ansiColor->integer )
512 Sys_AnsiColorPrint( msg );
513 else
514 fputs( msg, stderr );
515
516 if (!ttycon_on) {
517 // CON_Hide didn't do anything.
518 return;
519 }
520
521 // Only print prompt when msg ends with a newline, otherwise the console
522 // might get garbled when output does not fit on one line.
523 if (msg[strlen(msg) - 1] == '\n') {
524 CON_Show();
525
526 // Run CON_Show the number of times it was deferred.
527 while (ttycon_show_overdue > 0) {
528 CON_Show();
529 ttycon_show_overdue--;
530 }
531 }
532 else
533 {
534 // Defer calling CON_Show
535 ttycon_show_overdue++;
536 }
537 }