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.58 2015/04/08 02:12:11 zy 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(GS *);
36static int	cl_ex_init(SCR *);
37static void	cl_freecap(CL_PRIVATE *);
38static int	cl_vi_end(GS *);
39static int	cl_vi_init(SCR *);
40static int	cl_putenv(char *, char *, u_long);
41
42/*
43 * cl_screen --
44 *	Switch screen types.
45 *
46 * PUBLIC: int cl_screen(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 ((!F_ISSET(sp, SC_SCR_EX | SC_SCR_VI) ||
62		     resizeterm(O_VAL(sp, O_LINES), O_VAL(sp, O_COLUMNS))) &&
63		    cl_quit(gp))
64			return (1);
65		F_CLR(gp, G_SRESTART);
66	}
67
68	/* See if we're already in the right mode. */
69	if ((LF_ISSET(SC_EX) && F_ISSET(sp, SC_SCR_EX)) ||
70	    (LF_ISSET(SC_VI) && F_ISSET(sp, SC_SCR_VI)))
71		return (0);
72
73	/*
74	 * Fake leaving ex mode.
75	 *
76	 * We don't actually exit ex or vi mode unless forced (e.g. by a window
77	 * size change).  This is because many curses implementations can't be
78	 * called twice in a single program.  Plus, it's faster.  If the editor
79	 * "leaves" vi to enter ex, when it exits ex we'll just fall back into
80	 * vi.
81	 */
82	if (F_ISSET(sp, SC_SCR_EX))
83		F_CLR(sp, SC_SCR_EX);
84
85	/*
86	 * Fake leaving vi mode.
87	 *
88	 * Clear out the rest of the screen if we're in the middle of a split
89	 * screen.  Move to the last line in the current screen -- this makes
90	 * terminal scrolling happen naturally.  Note: *don't* move past the
91	 * end of the screen, as there are ex commands (e.g., :read ! cat file)
92	 * that don't want to.  Don't clear the info line, its contents may be
93	 * valid, e.g. :file|append.
94	 */
95	if (F_ISSET(sp, SC_SCR_VI)) {
96		F_CLR(sp, SC_SCR_VI);
97
98		if (TAILQ_NEXT(sp, q) != NULL) {
99			(void)wmove(win, RLNO(sp, sp->rows), 0);
100			wclrtobot(win);
101		}
102		(void)wmove(win, RLNO(sp, sp->rows) - 1, 0);
103		wrefresh(win);
104	}
105
106	/* Enter the requested mode. */
107	if (LF_ISSET(SC_EX)) {
108		if (cl_ex_init(sp))
109			return (1);
110		F_SET(clp, CL_IN_EX | CL_SCR_EX_INIT);
111
112		/*
113		 * If doing an ex screen for ex mode, move to the last line
114		 * on the screen.
115		 */
116		if (F_ISSET(sp, SC_EX) && clp->cup != NULL)
117			tputs(tgoto(clp->cup,
118			    0, O_VAL(sp, O_LINES) - 1), 1, cl_putchar);
119	} else {
120		if (cl_vi_init(sp))
121			return (1);
122		F_CLR(clp, CL_IN_EX);
123		F_SET(clp, CL_SCR_VI_INIT);
124	}
125	return (0);
126}
127
128/*
129 * cl_quit --
130 *	Shutdown the screens.
131 *
132 * PUBLIC: int cl_quit(GS *);
133 */
134int
135cl_quit(GS *gp)
136{
137	CL_PRIVATE *clp;
138	int rval;
139
140	rval = 0;
141	clp = GCLP(gp);
142
143	/*
144	 * If we weren't really running, ignore it.  This happens if the
145	 * screen changes size before we've called curses.
146	 */
147	if (!F_ISSET(clp, CL_SCR_EX_INIT | CL_SCR_VI_INIT))
148		return (0);
149
150	/* Clean up the terminal mappings. */
151	if (cl_term_end(gp))
152		rval = 1;
153
154	/* Really leave vi mode. */
155	if (F_ISSET(clp, CL_STDIN_TTY) &&
156	    F_ISSET(clp, CL_SCR_VI_INIT) && cl_vi_end(gp))
157		rval = 1;
158
159	/* Really leave ex mode. */
160	if (F_ISSET(clp, CL_STDIN_TTY) &&
161	    F_ISSET(clp, CL_SCR_EX_INIT) && cl_ex_end(gp))
162		rval = 1;
163
164	/*
165	 * If we were running ex when we quit, or we're using an implementation
166	 * of curses where endwin() doesn't get this right, restore the original
167	 * terminal modes.
168	 *
169	 * XXX
170	 * We always do this because it's too hard to figure out what curses
171	 * implementations get it wrong.  It may discard type-ahead characters
172	 * from the tty queue.
173	 */
174	(void)tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, &clp->orig);
175
176	F_CLR(clp, CL_SCR_EX_INIT | CL_SCR_VI_INIT);
177	return (rval);
178}
179
180/*
181 * cl_vi_init --
182 *	Initialize the curses vi screen.
183 */
184static int
185cl_vi_init(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	 * The terminal is aways initialized, either in `main`, or by a
236	 * previous call to newterm(3X).
237	 */
238	(void)del_curterm(cur_term);
239
240	/*
241	 * We never have more than one SCREEN at a time, so set_term(NULL) will
242	 * give us the last SCREEN.
243	 */
244	errno = 0;
245	if (newterm(ttype, stdout, stdin) == NULL) {
246		if (errno)
247			msgq(sp, M_SYSERR, "%s", ttype);
248		else
249			msgq(sp, M_ERR, "%s: unknown terminal type", ttype);
250		return (1);
251	}
252
253	if (o_term == NULL)
254		unsetenv("TERM");
255	if (o_lines == NULL)
256		unsetenv("LINES");
257	if (o_cols == NULL)
258		unsetenv("COLUMNS");
259
260	/*
261	 * XXX
262	 * Someone got let out alone without adult supervision -- the SunOS
263	 * newterm resets the signal handlers.  There's a race, but it's not
264	 * worth closing.
265	 */
266	(void)sig_init(sp->gp, sp);
267
268	/*
269	 * We use raw mode.  What we want is 8-bit clean, however, signals
270	 * and flow control should continue to work.  Admittedly, it sounds
271	 * like cbreak, but it isn't.  Using cbreak() can get you additional
272	 * things like IEXTEN, which turns on flags like DISCARD and LNEXT.
273	 *
274	 * !!!
275	 * If raw isn't turning off echo and newlines, something's wrong.
276	 * However, it shouldn't hurt.
277	 */
278	noecho();			/* No character echo. */
279	nonl();				/* No CR/NL translation. */
280	raw();				/* 8-bit clean. */
281	idlok(stdscr, 1);		/* Use hardware insert/delete line. */
282
283	/* Put the cursor keys into application mode. */
284	(void)keypad(stdscr, TRUE);
285
286	/*
287	 * XXX
288	 * The screen TI sequence just got sent.  See the comment in
289	 * cl_funcs.c:cl_attr().
290	 */
291	clp->ti_te = TI_SENT;
292
293	/*
294	 * XXX
295	 * Historic implementations of curses handled SIGTSTP signals
296	 * in one of three ways.  They either:
297	 *
298	 *	1: Set their own handler, regardless.
299	 *	2: Did not set a handler if a handler was already installed.
300	 *	3: Set their own handler, but then called any previously set
301	 *	   handler after completing their own cleanup.
302	 *
303	 * We don't try and figure out which behavior is in place, we force
304	 * it to SIG_DFL after initializing the curses interface, which means
305	 * that curses isn't going to take the signal.  Since curses isn't
306	 * reentrant (i.e., the whole curses SIGTSTP interface is a fantasy),
307	 * we're doing The Right Thing.
308	 */
309	(void)signal(SIGTSTP, SIG_DFL);
310
311	/*
312	 * If flow control was on, turn it back on.  Turn signals on.  ISIG
313	 * turns on VINTR, VQUIT, VDSUSP and VSUSP.   The main curses code
314	 * already installed a handler for VINTR.  We're going to disable the
315	 * other three.
316	 *
317	 * XXX
318	 * We want to use ^Y as a vi scrolling command.  If the user has the
319	 * DSUSP character set to ^Y (common practice) clean it up.  As it's
320	 * equally possible that the user has VDSUSP set to 'a', we disable
321	 * it regardless.  It doesn't make much sense to suspend vi at read,
322	 * so I don't think anyone will care.  Alternatively, we could look
323	 * it up in the table of legal command characters and turn it off if
324	 * it matches one.  VDSUSP wasn't in POSIX 1003.1-1990, so we test for
325	 * it.
326	 *
327	 * XXX
328	 * We don't check to see if the user had signals enabled originally.
329	 * If they didn't, it's unclear what we're supposed to do here, but
330	 * it's also pretty unlikely.
331	 */
332	if (tcgetattr(STDIN_FILENO, &clp->vi_enter)) {
333		msgq(sp, M_SYSERR, "tcgetattr");
334		goto err;
335	}
336	if (clp->orig.c_iflag & IXON)
337		clp->vi_enter.c_iflag |= IXON;
338	if (clp->orig.c_iflag & IXOFF)
339		clp->vi_enter.c_iflag |= IXOFF;
340
341	clp->vi_enter.c_lflag |= ISIG;
342#ifdef VDSUSP
343	clp->vi_enter.c_cc[VDSUSP] = _POSIX_VDISABLE;
344#endif
345	clp->vi_enter.c_cc[VQUIT] = _POSIX_VDISABLE;
346	clp->vi_enter.c_cc[VSUSP] = _POSIX_VDISABLE;
347
348	/*
349	 * XXX
350	 * OSF/1 doesn't turn off the <discard>, <literal-next> or <status>
351	 * characters when curses switches into raw mode.  It should be OK
352	 * to do it explicitly for everyone.
353	 */
354#ifdef VDISCARD
355	clp->vi_enter.c_cc[VDISCARD] = _POSIX_VDISABLE;
356#endif
357#ifdef VLNEXT
358	clp->vi_enter.c_cc[VLNEXT] = _POSIX_VDISABLE;
359#endif
360#ifdef VSTATUS
361	clp->vi_enter.c_cc[VSTATUS] = _POSIX_VDISABLE;
362#endif
363
364	/* Initialize terminal based information. */
365	if (cl_term_init(sp))
366		goto err;
367
368fast:	/* Set the terminal modes. */
369	if (tcsetattr(STDIN_FILENO, TCSASOFT | TCSADRAIN, &clp->vi_enter)) {
370		if (errno == EINTR)
371			goto fast;
372		msgq(sp, M_SYSERR, "tcsetattr");
373err:		(void)cl_vi_end(sp->gp);
374		return (1);
375	}
376	return (0);
377}
378
379/*
380 * cl_vi_end --
381 *	Shutdown the vi screen.
382 */
383static int
384cl_vi_end(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	/* Free the SCREEN created by newterm(3X). */
413	delscreen(set_term(NULL));
414
415	/*
416	 * XXX
417	 * The screen TE sequence just got sent.  See the comment in
418	 * cl_funcs.c:cl_attr().
419	 */
420	clp->ti_te = TE_SENT;
421
422	return (0);
423}
424
425/*
426 * cl_ex_init --
427 *	Initialize the ex screen.
428 */
429static int
430cl_ex_init(SCR *sp)
431{
432	CL_PRIVATE *clp;
433
434	clp = CLP(sp);
435
436	/* If already initialized, just set the terminal modes. */
437	if (F_ISSET(clp, CL_SCR_EX_INIT))
438		goto fast;
439
440	/* If not reading from a file, we're done. */
441	if (!F_ISSET(clp, CL_STDIN_TTY))
442		return (0);
443
444	/* Get the ex termcap/terminfo strings. */
445	(void)cl_getcap(sp, "cup", &clp->cup);
446	(void)cl_getcap(sp, "smso", &clp->smso);
447	(void)cl_getcap(sp, "rmso", &clp->rmso);
448	(void)cl_getcap(sp, "el", &clp->el);
449	(void)cl_getcap(sp, "cuu1", &clp->cuu1);
450
451	/* Enter_standout_mode and exit_standout_mode are paired. */
452	if (clp->smso == NULL || clp->rmso == NULL) {
453		if (clp->smso != NULL) {
454			free(clp->smso);
455			clp->smso = NULL;
456		}
457		if (clp->rmso != NULL) {
458			free(clp->rmso);
459			clp->rmso = NULL;
460		}
461	}
462
463	/*
464	 * Turn on canonical mode, with normal input and output processing.
465	 * Start with the original terminal settings as the user probably
466	 * had them (including any local extensions) set correctly for the
467	 * current terminal.
468	 *
469	 * !!!
470	 * We can't get everything that we need portably; for example, ONLCR,
471	 * mapping <newline> to <carriage-return> on output isn't required
472	 * by POSIX 1003.1b-1993.  If this turns out to be a problem, then
473	 * we'll either have to play some games on the mapping, or we'll have
474	 * to make all ex printf's output \r\n instead of \n.
475	 */
476	clp->ex_enter = clp->orig;
477	clp->ex_enter.c_lflag  |= ECHO | ECHOE | ECHOK | ICANON | IEXTEN | ISIG;
478#ifdef ECHOCTL
479	clp->ex_enter.c_lflag |= ECHOCTL;
480#endif
481#ifdef ECHOKE
482	clp->ex_enter.c_lflag |= ECHOKE;
483#endif
484	clp->ex_enter.c_iflag |= ICRNL;
485	clp->ex_enter.c_oflag |= OPOST;
486#ifdef ONLCR
487	clp->ex_enter.c_oflag |= ONLCR;
488#endif
489
490fast:	if (tcsetattr(STDIN_FILENO, TCSADRAIN | TCSASOFT, &clp->ex_enter)) {
491		if (errno == EINTR)
492			goto fast;
493		msgq(sp, M_SYSERR, "tcsetattr");
494		return (1);
495	}
496	return (0);
497}
498
499/*
500 * cl_ex_end --
501 *	Shutdown the ex screen.
502 */
503static int
504cl_ex_end(GS *gp)
505{
506	CL_PRIVATE *clp;
507
508	clp = GCLP(gp);
509
510	cl_freecap(clp);
511
512	return (0);
513}
514
515/*
516 * cl_getcap --
517 *	Retrieve termcap/terminfo strings.
518 *
519 * PUBLIC: int cl_getcap(SCR *, char *, char **);
520 */
521int
522cl_getcap(SCR *sp, char *name, char **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 */
539static void
540cl_freecap(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	/* Required by libcursesw :) */
563	if (clp->cw.bp1.c != NULL) {
564		free(clp->cw.bp1.c);
565		clp->cw.bp1.c = NULL;
566		clp->cw.blen1 = 0;
567	}
568}
569
570/*
571 * cl_putenv --
572 *	Put a value into the environment.
573 */
574static int
575cl_putenv(char *name, char *str, u_long value)
576{
577	char buf[40];
578
579	if (str == NULL) {
580		(void)snprintf(buf, sizeof(buf), "%lu", value);
581		return (setenv(name, buf, 1));
582	} else
583		return (setenv(name, str, 1));
584}
585