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