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