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