1/*
2 * Copyright (C) 1984-2012  Mark Nudelman
3 * Modified for use with illumos by Garrett D'Amore.
4 * Copyright 2014 Garrett D'Amore <garrett@damore.org>
5 *
6 * You may distribute under the terms of either the GNU General Public
7 * License or the Less License, as specified in the README file.
8 *
9 * For more information, see the README file.
10 */
11
12/*
13 * Routines which deal with the characteristics of the terminal.
14 * Uses termcap to be as terminal-independent as possible.
15 */
16
17#include <sys/ioctl.h>
18
19#include <err.h>
20#include <term.h>
21#include <termios.h>
22
23#include "cmd.h"
24#include "less.h"
25
26#define	DEFAULT_TERM		"unknown"
27
28/*
29 * Strings passed to tputs() to do various terminal functions.
30 */
31static char
32	*sc_home,		/* Cursor home */
33	*sc_addline,		/* Add line, scroll down following lines */
34	*sc_lower_left,		/* Cursor to last line, first column */
35	*sc_return,		/* Cursor to beginning of current line */
36	*sc_move,		/* General cursor positioning */
37	*sc_clear,		/* Clear screen */
38	*sc_eol_clear,		/* Clear to end of line */
39	*sc_eos_clear,		/* Clear to end of screen */
40	*sc_s_in,		/* Enter standout (highlighted) mode */
41	*sc_s_out,		/* Exit standout mode */
42	*sc_u_in,		/* Enter underline mode */
43	*sc_u_out,		/* Exit underline mode */
44	*sc_b_in,		/* Enter bold mode */
45	*sc_b_out,		/* Exit bold mode */
46	*sc_bl_in,		/* Enter blink mode */
47	*sc_bl_out,		/* Exit blink mode */
48	*sc_visual_bell,	/* Visual bell (flash screen) sequence */
49	*sc_backspace,		/* Backspace cursor */
50	*sc_s_keypad,		/* Start keypad mode */
51	*sc_e_keypad,		/* End keypad mode */
52	*sc_init,		/* Startup terminal initialization */
53	*sc_deinit;		/* Exit terminal de-initialization */
54
55static int init_done = 0;
56
57int auto_wrap;			/* Terminal does \r\n when write past margin */
58int ignaw;			/* Terminal ignores \n immediately after wrap */
59int erase_char;			/* The user's erase char */
60int erase2_char;		/* The user's other erase char */
61int kill_char;			/* The user's line-kill char */
62int werase_char;		/* The user's word-erase char */
63int sc_width, sc_height;	/* Height & width of screen */
64int bo_s_width, bo_e_width;	/* Printing width of boldface seq */
65int ul_s_width, ul_e_width;	/* Printing width of underline seq */
66int so_s_width, so_e_width;	/* Printing width of standout seq */
67int bl_s_width, bl_e_width;	/* Printing width of blink seq */
68int can_goto_line;		/* Can move cursor to any line */
69int missing_cap = 0;		/* Some capability is missing */
70static int above_mem;		/* Memory retained above screen */
71static int below_mem;		/* Memory retained below screen */
72
73static int attrmode = AT_NORMAL;
74extern int binattr;
75
76static char *cheaper(char *, char *, char *);
77static void tmodes(char *, char *, char **, char **, char *, char *);
78
79extern int quiet;		/* If VERY_QUIET, use visual bell for bell */
80extern int no_back_scroll;
81extern int swindow;
82extern int no_init;
83extern int no_keypad;
84extern int wscroll;
85extern int screen_trashed;
86extern int tty;
87extern int top_scroll;
88extern int oldbot;
89extern int hilite_search;
90
91/*
92 * Change terminal to "raw mode", or restore to "normal" mode.
93 * "Raw mode" means
94 *	1. An outstanding read will complete on receipt of a single keystroke.
95 *	2. Input is not echoed.
96 *	3. On output, \n is mapped to \r\n.
97 *	4. \t is NOT expanded into spaces.
98 *	5. Signal-causing characters such as ctrl-C (interrupt),
99 *	   etc. are NOT disabled.
100 * It doesn't matter whether an input \n is mapped to \r, or vice versa.
101 */
102void
103raw_mode(int on)
104{
105	static int curr_on = 0;
106	struct termios s;
107	static struct termios save_term;
108	static int saved_term = 0;
109
110	if (on == curr_on)
111		return;
112	erase2_char = '\b'; /* in case OS doesn't know about erase2 */
113
114	if (on) {
115		/*
116		 * Get terminal modes.
117		 */
118		(void) tcgetattr(tty, &s);
119
120		/*
121		 * Save modes and set certain variables dependent on modes.
122		 */
123		if (!saved_term) {
124			save_term = s;
125			saved_term = 1;
126		}
127
128		erase_char = s.c_cc[VERASE];
129#ifdef VERASE2
130		erase2_char = s.c_cc[VERASE2];
131#endif
132		kill_char = s.c_cc[VKILL];
133#ifdef VWERASE
134		werase_char = s.c_cc[VWERASE];
135#endif
136
137		/*
138		 * Set the modes to the way we want them.
139		 */
140		s.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL);
141
142#ifndef	TAB3
143#define	TAB3	0	/* Its a lie, but TAB3 isn't defined by POSIX. */
144#endif
145		s.c_oflag |= (TAB3 | OPOST | ONLCR);
146		s.c_oflag &= ~(OCRNL | ONOCR | ONLRET);
147		s.c_cc[VMIN] = 1;
148		s.c_cc[VTIME] = 0;
149#ifdef VLNEXT
150		s.c_cc[VLNEXT] = 0;
151#endif
152#ifdef VDSUSP
153		s.c_cc[VDSUSP] = 0;
154#endif
155	} else {
156		/*
157		 * Restore saved modes.
158		 */
159		s = save_term;
160	}
161	(void) tcsetattr(tty, TCSASOFT | TCSADRAIN, &s);
162	curr_on = on;
163}
164
165/*
166 * Some glue to prevent calling termcap functions if tgetent() failed.
167 */
168static int hardcopy;
169
170/*
171 * Get size of the output screen.
172 */
173static void
174scrsize(void)
175{
176	int sys_height = 0, sys_width = 0, n;
177	struct winsize w;
178	char *s;
179
180#define	DEF_SC_WIDTH	80
181#define	DEF_SC_HEIGHT	24
182
183	if (ioctl(2, TIOCGWINSZ, &w) == 0) {
184		if (w.ws_row > 0)
185			sys_height = w.ws_row;
186		if (w.ws_col > 0)
187			sys_width = w.ws_col;
188	}
189
190	if (sys_height > 0)
191		sc_height = sys_height;
192	else if ((s = lgetenv("LINES")) != NULL)
193		sc_height = atoi(s);
194	else if (!hardcopy && (n = lines) > 0)
195		sc_height = n;
196	if (sc_height <= 0)
197		sc_height = DEF_SC_HEIGHT;
198
199	if (sys_width > 0)
200		sc_width = sys_width;
201	else if ((s = lgetenv("COLUMNS")) != NULL)
202		sc_width = atoi(s);
203	else if (!hardcopy && (n = columns) > 0)
204		sc_width = n;
205	if (sc_width <= 0)
206		sc_width = DEF_SC_WIDTH;
207}
208
209/*
210 * Return the characters actually input by a "special" key.
211 */
212char *
213special_key_str(int key)
214{
215	char *s;
216	static char ctrlk[] = { CONTROL('K'), 0 };
217
218	if (hardcopy)
219		return (NULL);
220
221	switch (key) {
222	case SK_RIGHT_ARROW:
223		s = key_right;
224		break;
225	case SK_LEFT_ARROW:
226		s = key_left;
227		break;
228	case SK_UP_ARROW:
229		s = key_up;
230		break;
231	case SK_DOWN_ARROW:
232		s = key_down;
233		break;
234	case SK_PAGE_UP:
235		s = key_ppage;
236		break;
237	case SK_PAGE_DOWN:
238		s = key_npage;
239		break;
240	case SK_HOME:
241		s = key_home;
242		break;
243	case SK_END:
244		s = key_end;
245		break;
246	case SK_DELETE:
247		s = key_dc;
248		if (s == NULL) {
249			s = "\177\0";
250		}
251		break;
252	case SK_CONTROL_K:
253		s = ctrlk;
254		break;
255	default:
256		return (NULL);
257	}
258	return (s);
259}
260
261/*
262 * Get terminal capabilities via termcap.
263 */
264void
265get_term(void)
266{
267	char *t1, *t2;
268	char *term;
269	int  err;
270
271	/*
272	 * Find out what kind of terminal this is.
273	 */
274	if ((term = lgetenv("TERM")) == NULL)
275		term = DEFAULT_TERM;
276	hardcopy = 0;
277
278	if (setupterm(term, 1, &err) < 0) {
279		if (err == 1)
280			hardcopy = 1;
281		else
282			errx(1, "%s: unknown terminal type", term);
283	}
284	if (hard_copy == 1)
285		hardcopy = 1;
286
287	/*
288	 * Get size of the screen.
289	 */
290	scrsize();
291	pos_init();
292
293	auto_wrap = hardcopy ? 0 : auto_right_margin;
294	ignaw = hardcopy ? 0 : eat_newline_glitch;
295	above_mem = hardcopy ? 0 : memory_above;
296	below_mem = hardcopy ? 0 : memory_below;
297
298	/*
299	 * Assumes termcap variable "sg" is the printing width of:
300	 * the standout sequence, the end standout sequence,
301	 * the underline sequence, the end underline sequence,
302	 * the boldface sequence, and the end boldface sequence.
303	 */
304	if (hardcopy || (so_s_width = magic_cookie_glitch) < 0)
305		so_s_width = 0;
306	so_e_width = so_s_width;
307
308	bo_s_width = bo_e_width = so_s_width;
309	ul_s_width = ul_e_width = so_s_width;
310	bl_s_width = bl_e_width = so_s_width;
311
312	if (so_s_width > 0 || so_e_width > 0)
313		/*
314		 * Disable highlighting by default on magic cookie terminals.
315		 * Turning on highlighting might change the displayed width
316		 * of a line, causing the display to get messed up.
317		 * The user can turn it back on with -g,
318		 * but she won't like the results.
319		 */
320		hilite_search = 0;
321
322	/*
323	 * Get various string-valued capabilities.
324	 */
325
326	sc_s_keypad = keypad_xmit;
327	if (hardcopy || sc_s_keypad == NULL)
328		sc_s_keypad = "";
329	sc_e_keypad = keypad_local;
330	if (hardcopy || sc_e_keypad == NULL)
331		sc_e_keypad = "";
332
333	sc_init = enter_ca_mode;
334	if (hardcopy || sc_init == NULL)
335		sc_init = "";
336
337	sc_deinit = exit_ca_mode;
338	if (hardcopy || sc_deinit == NULL)
339		sc_deinit = "";
340
341	sc_eol_clear = clr_eol;
342	if (hardcopy || sc_eol_clear == NULL || *sc_eol_clear == '\0') {
343		missing_cap = 1;
344		sc_eol_clear = "";
345	}
346
347	sc_eos_clear = clr_eos;
348	if (below_mem &&
349	    (hardcopy || sc_eos_clear == NULL || *sc_eos_clear == '\0')) {
350		missing_cap = 1;
351		sc_eos_clear = "";
352	}
353
354	sc_clear = clear_screen;
355	if (hardcopy || sc_clear == NULL || *sc_clear == '\0') {
356		missing_cap = 1;
357		sc_clear = "\n\n";
358	}
359
360	sc_move = cursor_address;
361	if (hardcopy || sc_move == NULL || *sc_move == '\0') {
362		/*
363		 * This is not an error here, because we don't
364		 * always need sc_move.
365		 * We need it only if we don't have home or lower-left.
366		 */
367		sc_move = "";
368		can_goto_line = 0;
369	} else {
370		can_goto_line = 1;
371	}
372
373	tmodes(enter_standout_mode, exit_standout_mode, &sc_s_in, &sc_s_out,
374	    "", "");
375	tmodes(enter_underline_mode, exit_underline_mode, &sc_u_in, &sc_u_out,
376	    sc_s_in, sc_s_out);
377	tmodes(enter_bold_mode, exit_attribute_mode, &sc_b_in, &sc_b_out,
378	    sc_s_in, sc_s_out);
379	tmodes(enter_blink_mode, exit_attribute_mode, &sc_bl_in, &sc_bl_out,
380	    sc_s_in, sc_s_out);
381
382	sc_visual_bell = flash_screen;
383	if (hardcopy || sc_visual_bell == NULL)
384		sc_visual_bell = "";
385
386	sc_backspace = "\b";
387
388	/*
389	 * Choose between using "ho" and "cm" ("home" and "cursor move")
390	 * to move the cursor to the upper left corner of the screen.
391	 */
392	t1 = cursor_home;
393	if (hardcopy || t1 == NULL)
394		t1 = "";
395	if (*sc_move == '\0') {
396		t2 = "";
397	} else {
398		t2 = estrdup(tparm(sc_move, 0, 0, 0, 0, 0, 0, 0, 0, 0));
399	}
400	sc_home = cheaper(t1, t2, "|\b^");
401
402	/*
403	 * Choose between using "ll" and "cm"  ("lower left" and "cursor move")
404	 * to move the cursor to the lower left corner of the screen.
405	 */
406	t1 = cursor_to_ll;
407	if (hardcopy || t1 == NULL)
408		t1 = "";
409	if (*sc_move == '\0') {
410		t2 = "";
411	} else {
412		t2 = estrdup(tparm(sc_move, sc_height-1,
413		    0, 0, 0, 0, 0, 0, 0, 0));
414	}
415	sc_lower_left = cheaper(t1, t2, "\r");
416
417	/*
418	 * Get carriage return string.
419	 */
420	sc_return = carriage_return;
421	if (hardcopy || sc_return == NULL)
422		sc_return = "\r";
423
424	/*
425	 * Choose between using insert_line or scroll_reverse
426	 * to add a line at the top of the screen.
427	 */
428	t1 = insert_line;
429	if (hardcopy || t1 == NULL)
430		t1 = "";
431	t2 = scroll_reverse;
432	if (hardcopy || t2 == NULL)
433		t2 = "";
434	if (above_mem)
435		sc_addline = t1;
436	else
437		sc_addline = cheaper(t1, t2, "");
438	if (*sc_addline == '\0') {
439		/*
440		 * Force repaint on any backward movement.
441		 */
442		no_back_scroll = 1;
443	}
444}
445
446/*
447 * Return the cost of displaying a termcap string.
448 * We use the trick of calling tputs, but as a char printing function
449 * we give it inc_costcount, which just increments "costcount".
450 * This tells us how many chars would be printed by using this string.
451 * {{ Couldn't we just use strlen? }}
452 */
453static int costcount;
454
455static int
456inc_costcount(int c)
457{
458	costcount++;
459	return (c);
460}
461
462static int
463cost(char *t)
464{
465	costcount = 0;
466	(void) tputs(t, sc_height, inc_costcount);
467	return (costcount);
468}
469
470/*
471 * Return the "best" of the two given termcap strings.
472 * The best, if both exist, is the one with the lower
473 * cost (see cost() function).
474 */
475static char *
476cheaper(char *t1, char *t2, char *def)
477{
478	if (*t1 == '\0' && *t2 == '\0') {
479		missing_cap = 1;
480		return (def);
481	}
482	if (*t1 == '\0')
483		return (t2);
484	if (*t2 == '\0')
485		return (t1);
486	if (cost(t1) < cost(t2))
487		return (t1);
488	return (t2);
489}
490
491static void
492tmodes(char *incap, char *outcap, char **instr, char **outstr,
493    char *def_instr, char *def_outstr)
494{
495	if (hardcopy) {
496		*instr = "";
497		*outstr = "";
498		return;
499	}
500
501	*instr = incap;
502	*outstr = outcap;
503
504	if (*instr == NULL) {
505		/* Use defaults. */
506		*instr = def_instr;
507		*outstr = def_outstr;
508		return;
509	}
510
511	if (*outstr == NULL)
512		/* No specific out capability; use exit_attribute_mode. */
513		*outstr = exit_attribute_mode;
514	if (*outstr == NULL)
515		/* Don't even have that, use an empty string */
516		*outstr = "";
517}
518
519/*
520 * Below are the functions which perform all the
521 * terminal-specific screen manipulation.
522 */
523
524/*
525 * Initialize terminal
526 */
527void
528init(void)
529{
530	if (!no_init)
531		(void) tputs(sc_init, sc_height, putchr);
532	if (!no_keypad)
533		(void) tputs(sc_s_keypad, sc_height, putchr);
534	if (top_scroll) {
535		int i;
536
537		/*
538		 * This is nice to terminals with no alternate screen,
539		 * but with saved scrolled-off-the-top lines.  This way,
540		 * no previous line is lost, but we start with a whole
541		 * screen to ourself.
542		 */
543		for (i = 1; i < sc_height; i++)
544			(void) putchr('\n');
545	} else
546		line_left();
547	init_done = 1;
548}
549
550/*
551 * Deinitialize terminal
552 */
553void
554deinit(void)
555{
556	if (!init_done)
557		return;
558	if (!no_keypad)
559		(void) tputs(sc_e_keypad, sc_height, putchr);
560	if (!no_init)
561		(void) tputs(sc_deinit, sc_height, putchr);
562	init_done = 0;
563}
564
565/*
566 * Home cursor (move to upper left corner of screen).
567 */
568void
569home(void)
570{
571	(void) tputs(sc_home, 1, putchr);
572}
573
574/*
575 * Add a blank line (called with cursor at home).
576 * Should scroll the display down.
577 */
578void
579add_line(void)
580{
581	(void) tputs(sc_addline, sc_height, putchr);
582}
583
584/*
585 * Move cursor to lower left corner of screen.
586 */
587void
588lower_left(void)
589{
590	(void) tputs(sc_lower_left, 1, putchr);
591}
592
593/*
594 * Move cursor to left position of current line.
595 */
596void
597line_left(void)
598{
599	(void) tputs(sc_return, 1, putchr);
600}
601
602/*
603 * Goto a specific line on the screen.
604 */
605void
606goto_line(int slinenum)
607{
608	(void) tputs(tparm(sc_move, slinenum, 0, 0, 0, 0, 0, 0, 0, 0), 1,
609	    putchr);
610}
611
612/*
613 * Output the "visual bell", if there is one.
614 */
615void
616vbell(void)
617{
618	if (*sc_visual_bell == '\0')
619		return;
620	(void) tputs(sc_visual_bell, sc_height, putchr);
621}
622
623/*
624 * Make a noise.
625 */
626static void
627beep(void)
628{
629	(void) putchr(CONTROL('G'));
630}
631
632/*
633 * Ring the terminal bell.
634 */
635void
636ring_bell(void)
637{
638	if (quiet == VERY_QUIET)
639		vbell();
640	else
641		beep();
642}
643
644/*
645 * Clear the screen.
646 */
647void
648do_clear(void)
649{
650	(void) tputs(sc_clear, sc_height, putchr);
651}
652
653/*
654 * Clear from the cursor to the end of the cursor's line.
655 * {{ This must not move the cursor. }}
656 */
657void
658clear_eol(void)
659{
660	(void) tputs(sc_eol_clear, 1, putchr);
661}
662
663/*
664 * Clear the current line.
665 * Clear the screen if there's off-screen memory below the display.
666 */
667static void
668clear_eol_bot(void)
669{
670	if (below_mem)
671		(void) tputs(sc_eos_clear, 1, putchr);
672	else
673		(void) tputs(sc_eol_clear, 1, putchr);
674}
675
676/*
677 * Clear the bottom line of the display.
678 * Leave the cursor at the beginning of the bottom line.
679 */
680void
681clear_bot(void)
682{
683	/*
684	 * If we're in a non-normal attribute mode, temporarily exit
685	 * the mode while we do the clear.  Some terminals fill the
686	 * cleared area with the current attribute.
687	 */
688	if (oldbot)
689		lower_left();
690	else
691		line_left();
692
693	if (attrmode == AT_NORMAL)
694		clear_eol_bot();
695	else
696	{
697		int saved_attrmode = attrmode;
698
699		at_exit();
700		clear_eol_bot();
701		at_enter(saved_attrmode);
702	}
703}
704
705void
706at_enter(int attr)
707{
708	attr = apply_at_specials(attr);
709
710	/* The one with the most priority is last.  */
711	if (attr & AT_UNDERLINE)
712		(void) tputs(sc_u_in, 1, putchr);
713	if (attr & AT_BOLD)
714		(void) tputs(sc_b_in, 1, putchr);
715	if (attr & AT_BLINK)
716		(void) tputs(sc_bl_in, 1, putchr);
717	if (attr & AT_STANDOUT)
718		(void) tputs(sc_s_in, 1, putchr);
719
720	attrmode = attr;
721}
722
723void
724at_exit(void)
725{
726	/* Undo things in the reverse order we did them.  */
727	if (attrmode & AT_STANDOUT)
728		(void) tputs(sc_s_out, 1, putchr);
729	if (attrmode & AT_BLINK)
730		(void) tputs(sc_bl_out, 1, putchr);
731	if (attrmode & AT_BOLD)
732		(void) tputs(sc_b_out, 1, putchr);
733	if (attrmode & AT_UNDERLINE)
734		(void) tputs(sc_u_out, 1, putchr);
735
736	attrmode = AT_NORMAL;
737}
738
739void
740at_switch(int attr)
741{
742	int new_attrmode = apply_at_specials(attr);
743	int ignore_modes = AT_ANSI;
744
745	if ((new_attrmode & ~ignore_modes) != (attrmode & ~ignore_modes)) {
746		at_exit();
747		at_enter(attr);
748	}
749}
750
751int
752is_at_equiv(int attr1, int attr2)
753{
754	attr1 = apply_at_specials(attr1);
755	attr2 = apply_at_specials(attr2);
756
757	return (attr1 == attr2);
758}
759
760int
761apply_at_specials(int attr)
762{
763	if (attr & AT_BINARY)
764		attr |= binattr;
765	if (attr & AT_HILITE)
766		attr |= AT_STANDOUT;
767	attr &= ~(AT_BINARY|AT_HILITE);
768
769	return (attr);
770}
771
772/*
773 * Output a plain backspace, without erasing the previous char.
774 */
775void
776putbs(void)
777{
778	(void) tputs(sc_backspace, 1, putchr);
779}
780