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