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