xref: /openbsd/usr.bin/vi/cl/cl_screen.c (revision 898184e3)
1 /*	$OpenBSD: cl_screen.c,v 1.19 2009/10/27 23:59:47 deraadt Exp $	*/
2 
3 /*-
4  * Copyright (c) 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  * Copyright (c) 1993, 1994, 1995, 1996
7  *	Keith Bostic.  All rights reserved.
8  *
9  * See the LICENSE file for redistribution information.
10  */
11 
12 #include "config.h"
13 
14 #include <sys/types.h>
15 #include <sys/queue.h>
16 
17 #include <bitstring.h>
18 #include <curses.h>
19 #include <errno.h>
20 #include <signal.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <term.h>
25 #include <termios.h>
26 #include <unistd.h>
27 
28 #include "../common/common.h"
29 #include "cl.h"
30 
31 static int	cl_ex_end(GS *);
32 static int	cl_ex_init(SCR *);
33 static void	cl_freecap(CL_PRIVATE *);
34 static int	cl_vi_end(GS *);
35 static int	cl_vi_init(SCR *);
36 static int	cl_putenv(char *, char *, u_long);
37 
38 /*
39  * cl_screen --
40  *	Switch screen types.
41  *
42  * PUBLIC: int cl_screen(SCR *, u_int32_t);
43  */
44 int
45 cl_screen(sp, flags)
46 	SCR *sp;
47 	u_int32_t flags;
48 {
49 	CL_PRIVATE *clp;
50 	GS *gp;
51 
52 	gp = sp->gp;
53 	clp = CLP(sp);
54 
55 	/* See if the current information is incorrect. */
56 	if (F_ISSET(gp, G_SRESTART)) {
57 		if (cl_quit(gp))
58 			return (1);
59 		F_CLR(gp, G_SRESTART);
60 	}
61 
62 	/* See if we're already in the right mode. */
63 	if ((LF_ISSET(SC_EX) && F_ISSET(sp, SC_SCR_EX)) ||
64 	    (LF_ISSET(SC_VI) && F_ISSET(sp, SC_SCR_VI)))
65 		return (0);
66 
67 	/*
68 	 * Fake leaving ex mode.
69 	 *
70 	 * We don't actually exit ex or vi mode unless forced (e.g. by a window
71 	 * size change).  This is because many curses implementations can't be
72 	 * called twice in a single program.  Plus, it's faster.  If the editor
73 	 * "leaves" vi to enter ex, when it exits ex we'll just fall back into
74 	 * vi.
75 	 */
76 	if (F_ISSET(sp, SC_SCR_EX))
77 		F_CLR(sp, SC_SCR_EX);
78 
79 	/*
80 	 * Fake leaving vi mode.
81 	 *
82 	 * Clear out the rest of the screen if we're in the middle of a split
83 	 * screen.  Move to the last line in the current screen -- this makes
84 	 * terminal scrolling happen naturally.  Note: *don't* move past the
85 	 * end of the screen, as there are ex commands (e.g., :read ! cat file)
86 	 * that don't want to.  Don't clear the info line, its contents may be
87 	 * valid, e.g. :file|append.
88 	 */
89 	if (F_ISSET(sp, SC_SCR_VI)) {
90 		F_CLR(sp, SC_SCR_VI);
91 
92 		if (CIRCLEQ_NEXT(sp, q) != CIRCLEQ_END(&gp->dq)) {
93 			(void)move(RLNO(sp, sp->rows), 0);
94 			clrtobot();
95 		}
96 		(void)move(RLNO(sp, sp->rows) - 1, 0);
97 		refresh();
98 	}
99 
100 	/* Enter the requested mode. */
101 	if (LF_ISSET(SC_EX)) {
102 		if (cl_ex_init(sp))
103 			return (1);
104 		F_SET(clp, CL_IN_EX | CL_SCR_EX_INIT);
105 
106 		/*
107 		 * If doing an ex screen for ex mode, move to the last line
108 		 * on the screen.
109 		 */
110 		if (F_ISSET(sp, SC_EX) && clp->cup != NULL)
111 			tputs(tgoto(clp->cup,
112 			    0, O_VAL(sp, O_LINES) - 1), 1, cl_putchar);
113 	} else {
114 		if (cl_vi_init(sp))
115 			return (1);
116 		F_CLR(clp, CL_IN_EX);
117 		F_SET(clp, CL_SCR_VI_INIT);
118 	}
119 	return (0);
120 }
121 
122 /*
123  * cl_quit --
124  *	Shutdown the screens.
125  *
126  * PUBLIC: int cl_quit(GS *);
127  */
128 int
129 cl_quit(gp)
130 	GS *gp;
131 {
132 	CL_PRIVATE *clp;
133 	int rval;
134 
135 	rval = 0;
136 	clp = GCLP(gp);
137 
138 	/*
139 	 * If we weren't really running, ignore it.  This happens if the
140 	 * screen changes size before we've called curses.
141 	 */
142 	if (!F_ISSET(clp, CL_SCR_EX_INIT | CL_SCR_VI_INIT))
143 		return (0);
144 
145 	/* Clean up the terminal mappings. */
146 	if (cl_term_end(gp))
147 		rval = 1;
148 
149 	/* Really leave vi mode. */
150 	if (F_ISSET(clp, CL_STDIN_TTY) &&
151 	    F_ISSET(clp, CL_SCR_VI_INIT) && cl_vi_end(gp))
152 		rval = 1;
153 
154 	/* Really leave ex mode. */
155 	if (F_ISSET(clp, CL_STDIN_TTY) &&
156 	    F_ISSET(clp, CL_SCR_EX_INIT) && cl_ex_end(gp))
157 		rval = 1;
158 
159 	/*
160 	 * If we were running ex when we quit, or we're using an implementation
161 	 * of curses where endwin() doesn't get this right, restore the original
162 	 * terminal modes.
163 	 *
164 	 * XXX
165 	 * We always do this because it's too hard to figure out what curses
166 	 * implementations get it wrong.  It may discard type-ahead characters
167 	 * from the tty queue.
168 	 */
169 	(void)tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, &clp->orig);
170 
171 	F_CLR(clp, CL_SCR_EX_INIT | CL_SCR_VI_INIT);
172 	return (rval);
173 }
174 
175 /*
176  * cl_vi_init --
177  *	Initialize the curses vi screen.
178  */
179 static int
180 cl_vi_init(sp)
181 	SCR *sp;
182 {
183 	CL_PRIVATE *clp;
184 	char *o_cols, *o_lines, *o_term, *ttype;
185 
186 	clp = CLP(sp);
187 
188 	/* If already initialized, just set the terminal modes. */
189 	if (F_ISSET(clp, CL_SCR_VI_INIT))
190 		goto fast;
191 
192 	/* Curses vi always reads from (and writes to) a terminal. */
193 	if (!F_ISSET(clp, CL_STDIN_TTY) || !isatty(STDOUT_FILENO)) {
194 		msgq(sp, M_ERR,
195 		    "016|Vi's standard input and output must be a terminal");
196 		return (1);
197 	}
198 
199 	/* We'll need a terminal type. */
200 	if (opts_empty(sp, O_TERM, 0))
201 		return (1);
202 	ttype = O_STR(sp, O_TERM);
203 
204 	/*
205 	 * XXX
206 	 * Changing the row/column and terminal values is done by putting them
207 	 * into the environment, which is then read by curses.  What this loses
208 	 * in ugliness, it makes up for in stupidity.  We can't simply put the
209 	 * values into the environment ourselves, because in the presence of a
210 	 * kernel mechanism for returning the window size, entering values into
211 	 * the environment will screw up future screen resizing events, e.g. if
212 	 * the user enters a :shell command and then resizes their window.  So,
213 	 * if they weren't already in the environment, we make sure to delete
214 	 * them immediately after setting them.
215 	 *
216 	 * XXX
217 	 * Putting the TERM variable into the environment is necessary, even
218 	 * though we're using newterm() here.  We may be using initscr() as
219 	 * the underlying function.
220 	 */
221 	o_term = getenv("TERM");
222 	cl_putenv("TERM", ttype, 0);
223 	o_lines = getenv("LINES");
224 	cl_putenv("LINES", NULL, (u_long)O_VAL(sp, O_LINES));
225 	o_cols = getenv("COLUMNS");
226 	cl_putenv("COLUMNS", NULL, (u_long)O_VAL(sp, O_COLUMNS));
227 
228 	/*
229 	 * We don't care about the SCREEN reference returned by newterm, we
230 	 * never have more than one SCREEN at a time.
231 	 *
232 	 * XXX
233 	 * The SunOS initscr() can't be called twice.  Don't even think about
234 	 * using it.  It fails in subtle ways (e.g. select(2) on fileno(stdin)
235 	 * stops working).  (The SVID notes that applications should only call
236 	 * initscr() once.)
237 	 *
238 	 * XXX
239 	 * The HP/UX newterm doesn't support the NULL first argument, so we
240 	 * have to specify the terminal type.
241 	 */
242 	errno = 0;
243 	if (newterm(ttype, stdout, stdin) == NULL) {
244 		if (errno)
245 			msgq(sp, M_SYSERR, "%s", ttype);
246 		else
247 			msgq(sp, M_ERR, "%s: unknown terminal type", ttype);
248 		return (1);
249 	}
250 
251 	if (o_term == NULL)
252 		unsetenv("TERM");
253 	if (o_lines == NULL)
254 		unsetenv("LINES");
255 	if (o_cols == NULL)
256 		unsetenv("COLUMNS");
257 
258 	/*
259 	 * XXX
260 	 * Someone got let out alone without adult supervision -- the SunOS
261 	 * newterm resets the signal handlers.  There's a race, but it's not
262 	 * worth closing.
263 	 */
264 	(void)sig_init(sp->gp, sp);
265 
266 	/*
267 	 * We use raw mode.  What we want is 8-bit clean, however, signals
268 	 * and flow control should continue to work.  Admittedly, it sounds
269 	 * like cbreak, but it isn't.  Using cbreak() can get you additional
270 	 * things like IEXTEN, which turns on flags like DISCARD and LNEXT.
271 	 *
272 	 * !!!
273 	 * If raw isn't turning off echo and newlines, something's wrong.
274 	 * However, it shouldn't hurt.
275 	 */
276 	noecho();			/* No character echo. */
277 	nonl();				/* No CR/NL translation. */
278 	raw();				/* 8-bit clean. */
279 	idlok(stdscr, 1);		/* Use hardware insert/delete line. */
280 
281 	/* Put the cursor keys into application mode. */
282 	(void)keypad(stdscr, TRUE);
283 
284 	/*
285 	 * XXX
286 	 * The screen TI sequence just got sent.  See the comment in
287 	 * cl_funcs.c:cl_attr().
288 	 */
289 	clp->ti_te = TI_SENT;
290 
291 	/*
292 	 * XXX
293 	 * Historic implementations of curses handled SIGTSTP signals
294 	 * in one of three ways.  They either:
295 	 *
296 	 *	1: Set their own handler, regardless.
297 	 *	2: Did not set a handler if a handler was already installed.
298 	 *	3: Set their own handler, but then called any previously set
299 	 *	   handler after completing their own cleanup.
300 	 *
301 	 * We don't try and figure out which behavior is in place, we force
302 	 * it to SIG_DFL after initializing the curses interface, which means
303 	 * that curses isn't going to take the signal.  Since curses isn't
304 	 * reentrant (i.e., the whole curses SIGTSTP interface is a fantasy),
305 	 * we're doing The Right Thing.
306 	 */
307 	(void)signal(SIGTSTP, SIG_DFL);
308 
309 	/*
310 	 * If flow control was on, turn it back on.  Turn signals on.  ISIG
311 	 * turns on VINTR, VQUIT, VDSUSP and VSUSP.   The main curses code
312 	 * already installed a handler for VINTR.  We're going to disable the
313 	 * other three.
314 	 *
315 	 * XXX
316 	 * We want to use ^Y as a vi scrolling command.  If the user has the
317 	 * DSUSP character set to ^Y (common practice) clean it up.  As it's
318 	 * equally possible that the user has VDSUSP set to 'a', we disable
319 	 * it regardless.  It doesn't make much sense to suspend vi at read,
320 	 * so I don't think anyone will care.  Alternatively, we could look
321 	 * it up in the table of legal command characters and turn it off if
322 	 * it matches one.  VDSUSP wasn't in POSIX 1003.1-1990, so we test for
323 	 * it.
324 	 *
325 	 * XXX
326 	 * We don't check to see if the user had signals enabled originally.
327 	 * If they didn't, it's unclear what we're supposed to do here, but
328 	 * it's also pretty unlikely.
329 	 */
330 	if (tcgetattr(STDIN_FILENO, &clp->vi_enter)) {
331 		msgq(sp, M_SYSERR, "tcgetattr");
332 		goto err;
333 	}
334 	if (clp->orig.c_iflag & IXON)
335 		clp->vi_enter.c_iflag |= IXON;
336 	if (clp->orig.c_iflag & IXOFF)
337 		clp->vi_enter.c_iflag |= IXOFF;
338 
339 	clp->vi_enter.c_lflag |= ISIG;
340 #ifdef VDSUSP
341 	clp->vi_enter.c_cc[VDSUSP] = _POSIX_VDISABLE;
342 #endif
343 	clp->vi_enter.c_cc[VQUIT] = _POSIX_VDISABLE;
344 	clp->vi_enter.c_cc[VSUSP] = _POSIX_VDISABLE;
345 
346 	/*
347 	 * XXX
348 	 * OSF/1 doesn't turn off the <discard>, <literal-next> or <status>
349 	 * characters when curses switches into raw mode.  It should be OK
350 	 * to do it explicitly for everyone.
351 	 */
352 #ifdef VDISCARD
353 	clp->vi_enter.c_cc[VDISCARD] = _POSIX_VDISABLE;
354 #endif
355 #ifdef VLNEXT
356 	clp->vi_enter.c_cc[VLNEXT] = _POSIX_VDISABLE;
357 #endif
358 #ifdef VSTATUS
359 	clp->vi_enter.c_cc[VSTATUS] = _POSIX_VDISABLE;
360 #endif
361 
362 	/* Initialize terminal based information. */
363 	if (cl_term_init(sp))
364 		goto err;
365 
366 fast:	/* Set the terminal modes. */
367 	if (tcsetattr(STDIN_FILENO, TCSASOFT | TCSADRAIN, &clp->vi_enter)) {
368 		if (errno == EINTR)
369 			goto fast;
370 		msgq(sp, M_SYSERR, "tcsetattr");
371 err:		(void)cl_vi_end(sp->gp);
372 		return (1);
373 	}
374 	return (0);
375 }
376 
377 /*
378  * cl_vi_end --
379  *	Shutdown the vi screen.
380  */
381 static int
382 cl_vi_end(gp)
383 	GS *gp;
384 {
385 	CL_PRIVATE *clp;
386 
387 	clp = GCLP(gp);
388 
389 	/* Restore the cursor keys to normal mode. */
390 	(void)keypad(stdscr, FALSE);
391 
392 	/*
393 	 * If we were running vi when we quit, scroll the screen up a single
394 	 * line so we don't lose any information.
395 	 *
396 	 * Move to the bottom of the window (some endwin implementations don't
397 	 * do this for you).
398 	 */
399 	if (!F_ISSET(clp, CL_IN_EX)) {
400 		(void)move(0, 0);
401 		(void)deleteln();
402 		(void)move(LINES - 1, 0);
403 		(void)refresh();
404 	}
405 
406 	cl_freecap(clp);
407 
408 	/* End curses window. */
409 	(void)endwin();
410 
411 	/*
412 	 * XXX
413 	 * The screen TE sequence just got sent.  See the comment in
414 	 * cl_funcs.c:cl_attr().
415 	 */
416 	clp->ti_te = TE_SENT;
417 
418 	return (0);
419 }
420 
421 /*
422  * cl_ex_init --
423  *	Initialize the ex screen.
424  */
425 static int
426 cl_ex_init(sp)
427 	SCR *sp;
428 {
429 	CL_PRIVATE *clp;
430 
431 	clp = CLP(sp);
432 
433 	/* If already initialized, just set the terminal modes. */
434 	if (F_ISSET(clp, CL_SCR_EX_INIT))
435 		goto fast;
436 
437 	/* If not reading from a file, we're done. */
438 	if (!F_ISSET(clp, CL_STDIN_TTY))
439 		return (0);
440 
441 	/* Get the ex termcap/terminfo strings. */
442 	(void)cl_getcap(sp, "cup", &clp->cup);
443 	(void)cl_getcap(sp, "smso", &clp->smso);
444 	(void)cl_getcap(sp, "rmso", &clp->rmso);
445 	(void)cl_getcap(sp, "el", &clp->el);
446 	(void)cl_getcap(sp, "cuu1", &clp->cuu1);
447 
448 	/* Enter_standout_mode and exit_standout_mode are paired. */
449 	if (clp->smso == NULL || clp->rmso == NULL) {
450 		if (clp->smso != NULL) {
451 			free(clp->smso);
452 			clp->smso = NULL;
453 		}
454 		if (clp->rmso != NULL) {
455 			free(clp->rmso);
456 			clp->rmso = NULL;
457 		}
458 	}
459 
460 	/*
461 	 * Turn on canonical mode, with normal input and output processing.
462 	 * Start with the original terminal settings as the user probably
463 	 * had them (including any local extensions) set correctly for the
464 	 * current terminal.
465 	 *
466 	 * !!!
467 	 * We can't get everything that we need portably; for example, ONLCR,
468 	 * mapping <newline> to <carriage-return> on output isn't required
469 	 * by POSIX 1003.1b-1993.  If this turns out to be a problem, then
470 	 * we'll either have to play some games on the mapping, or we'll have
471 	 * to make all ex printf's output \r\n instead of \n.
472 	 */
473 	clp->ex_enter = clp->orig;
474 	clp->ex_enter.c_lflag  |= ECHO | ECHOE | ECHOK | ICANON | IEXTEN | ISIG;
475 #ifdef ECHOCTL
476 	clp->ex_enter.c_lflag |= ECHOCTL;
477 #endif
478 #ifdef ECHOKE
479 	clp->ex_enter.c_lflag |= ECHOKE;
480 #endif
481 	clp->ex_enter.c_iflag |= ICRNL;
482 	clp->ex_enter.c_oflag |= OPOST;
483 #ifdef ONLCR
484 	clp->ex_enter.c_oflag |= ONLCR;
485 #endif
486 
487 fast:	if (tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, &clp->ex_enter)) {
488 		if (errno == EINTR)
489 			goto fast;
490 		msgq(sp, M_SYSERR, "tcsetattr");
491 		return (1);
492 	}
493 	return (0);
494 }
495 
496 /*
497  * cl_ex_end --
498  *	Shutdown the ex screen.
499  */
500 static int
501 cl_ex_end(gp)
502 	GS *gp;
503 {
504 	CL_PRIVATE *clp;
505 
506 	clp = GCLP(gp);
507 
508 	cl_freecap(clp);
509 
510 	return (0);
511 }
512 
513 /*
514  * cl_getcap --
515  *	Retrieve termcap/terminfo strings.
516  *
517  * PUBLIC: int cl_getcap(SCR *, char *, char **);
518  */
519 int
520 cl_getcap(sp, name, elementp)
521 	SCR *sp;
522 	char *name, **elementp;
523 {
524 	size_t len;
525 	char *t;
526 
527 	if ((t = tigetstr(name)) != NULL &&
528 	    t != (char *)-1 && (len = strlen(t)) != 0) {
529 		MALLOC_RET(sp, *elementp, char *, len + 1);
530 		memmove(*elementp, t, len + 1);
531 	}
532 	return (0);
533 }
534 
535 /*
536  * cl_freecap --
537  *	Free any allocated termcap/terminfo strings.
538  */
539 static void
540 cl_freecap(clp)
541 	CL_PRIVATE *clp;
542 {
543 	if (clp->el != NULL) {
544 		free(clp->el);
545 		clp->el = NULL;
546 	}
547 	if (clp->cup != NULL) {
548 		free(clp->cup);
549 		clp->cup = NULL;
550 	}
551 	if (clp->cuu1 != NULL) {
552 		free(clp->cuu1);
553 		clp->cuu1 = NULL;
554 	}
555 	if (clp->rmso != NULL) {
556 		free(clp->rmso);
557 		clp->rmso = NULL;
558 	}
559 	if (clp->smso != NULL) {
560 		free(clp->smso);
561 		clp->smso = NULL;
562 	}
563 }
564 
565 /*
566  * cl_putenv --
567  *	Put a value into the environment.
568  */
569 static int
570 cl_putenv(name, str, value)
571 	char *name, *str;
572 	u_long value;
573 
574 {
575 	char buf[40];
576 
577 	if (str == NULL) {
578 		(void)snprintf(buf, sizeof(buf), "%lu", value);
579 		return (setenv(name, buf, 1));
580 	} else
581 		return (setenv(name, str, 1));
582 }
583