1/****************************************************************************
2 * Copyright (c) 1998-2007,2008 Free Software Foundation, Inc.              *
3 *                                                                          *
4 * Permission is hereby granted, free of charge, to any person obtaining a  *
5 * copy of this software and associated documentation files (the            *
6 * "Software"), to deal in the Software without restriction, including      *
7 * without limitation the rights to use, copy, modify, merge, publish,      *
8 * distribute, distribute with modifications, sublicense, and/or sell       *
9 * copies of the Software, and to permit persons to whom the Software is    *
10 * furnished to do so, subject to the following conditions:                 *
11 *                                                                          *
12 * The above copyright notice and this permission notice shall be included  *
13 * in all copies or substantial portions of the Software.                   *
14 *                                                                          *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
16 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
17 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
18 * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
19 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
20 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
21 * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
22 *                                                                          *
23 * Except as contained in this notice, the name(s) of the above copyright   *
24 * holders shall not be used in advertising or otherwise to promote the     *
25 * sale, use or other dealings in this Software without prior written       *
26 * authorization.                                                           *
27 ****************************************************************************/
28
29/****************************************************************************
30 *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31 *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32 *     and: Thomas E. Dickey                        1996-on                 *
33 ****************************************************************************/
34
35/*-----------------------------------------------------------------
36 *
37 *	lib_doupdate.c
38 *
39 * 	The routine doupdate() and its dependents.
40 * 	All physical output is concentrated here (except _nc_outch()
41  *	in lib_tputs.c).
42 *
43 *-----------------------------------------------------------------*/
44
45#include <curses.priv.h>
46
47#if defined __HAIKU__ && defined __BEOS__
48#undef __BEOS__
49#endif
50
51#ifdef __BEOS__
52#undef false
53#undef true
54#include <OS.h>
55#endif
56
57#if defined(TRACE) && HAVE_SYS_TIMES_H && HAVE_TIMES
58#define USE_TRACE_TIMES 1
59#else
60#define USE_TRACE_TIMES 0
61#endif
62
63#if HAVE_SYS_TIME_H && HAVE_SYS_TIME_SELECT
64#include <sys/time.h>
65#endif
66
67#if USE_TRACE_TIMES
68#include <sys/times.h>
69#endif
70
71#if USE_FUNC_POLL
72#elif HAVE_SELECT
73#if HAVE_SYS_SELECT_H
74#include <sys/select.h>
75#endif
76#endif
77
78#include <ctype.h>
79#include <term.h>
80
81MODULE_ID("$Id: tty_update.c,v 1.246 2008/08/30 20:08:19 tom Exp $")
82
83/*
84 * This define controls the line-breakout optimization.  Every once in a
85 * while during screen refresh, we want to check for input and abort the
86 * update if there's some waiting.  CHECK_INTERVAL controls the number of
87 * changed lines to be emitted between input checks.
88 *
89 * Note: Input-check-and-abort is no longer done if the screen is being
90 * updated from scratch.  This is a feature, not a bug.
91 */
92#define CHECK_INTERVAL	5
93
94#define FILL_BCE() (SP->_coloron && !SP->_default_color && !back_color_erase)
95
96static const NCURSES_CH_T blankchar = NewChar(BLANK_TEXT);
97static NCURSES_CH_T normal = NewChar(BLANK_TEXT);
98
99/*
100 * Enable checking to see if doupdate and friends are tracking the true
101 * cursor position correctly.  NOTE: this is a debugging hack which will
102 * work ONLY on ANSI-compatible terminals!
103 */
104/* #define POSITION_DEBUG */
105
106static NCURSES_INLINE NCURSES_CH_T ClrBlank(WINDOW *win);
107static int ClrBottom(int total);
108static void ClearScreen(NCURSES_CH_T blank);
109static void ClrUpdate(void);
110static void DelChar(int count);
111static void InsStr(NCURSES_CH_T * line, int count);
112static void TransformLine(int const lineno);
113
114#ifdef POSITION_DEBUG
115/****************************************************************************
116 *
117 * Debugging code.  Only works on ANSI-standard terminals.
118 *
119 ****************************************************************************/
120
121static void
122position_check(int expected_y, int expected_x, char *legend)
123/* check to see if the real cursor position matches the virtual */
124{
125    char buf[20];
126    char *s;
127    int y, x;
128
129    if (!_nc_tracing || (expected_y < 0 && expected_x < 0))
130	return;
131
132    _nc_flush();
133    memset(buf, '\0', sizeof(buf));
134    putp("\033[6n");		/* only works on ANSI-compatibles */
135    _nc_flush();
136    *(s = buf) = 0;
137    do {
138	int ask = sizeof(buf) - 1 - (s - buf);
139	int got = read(0, s, ask);
140	if (got == 0)
141	    break;
142	s += got;
143    } while (strchr(buf, 'R') == 0);
144    _tracef("probe returned %s", _nc_visbuf(buf));
145
146    /* try to interpret as a position report */
147    if (sscanf(buf, "\033[%d;%dR", &y, &x) != 2) {
148	_tracef("position probe failed in %s", legend);
149    } else {
150	if (expected_x < 0)
151	    expected_x = x - 1;
152	if (expected_y < 0)
153	    expected_y = y - 1;
154	if (y - 1 != expected_y || x - 1 != expected_x) {
155	    beep();
156	    tputs(tparm("\033[%d;%dH", expected_y + 1, expected_x + 1), 1, _nc_outch);
157	    _tracef("position seen (%d, %d) doesn't match expected one (%d, %d) in %s",
158		    y - 1, x - 1, expected_y, expected_x, legend);
159	} else {
160	    _tracef("position matches OK in %s", legend);
161	}
162    }
163}
164#else
165#define position_check(expected_y, expected_x, legend)	/* nothing */
166#endif /* POSITION_DEBUG */
167
168/****************************************************************************
169 *
170 * Optimized update code
171 *
172 ****************************************************************************/
173
174static NCURSES_INLINE void
175GoTo(int const row, int const col)
176{
177    TR(TRACE_MOVE, ("GoTo(%d, %d) from (%d, %d)",
178		    row, col, SP->_cursrow, SP->_curscol));
179
180    position_check(SP->_cursrow, SP->_curscol, "GoTo");
181
182    mvcur(SP->_cursrow, SP->_curscol, row, col);
183    position_check(SP->_cursrow, SP->_curscol, "GoTo2");
184}
185
186static NCURSES_INLINE void
187PutAttrChar(CARG_CH_T ch)
188{
189    int chlen = 1;
190    NCURSES_CH_T my_ch;
191    PUTC_DATA;
192    NCURSES_CH_T tilde;
193    NCURSES_CH_T attr = CHDEREF(ch);
194
195    TR(TRACE_CHARPUT, ("PutAttrChar(%s) at (%d, %d)",
196		       _tracech_t(ch),
197		       SP->_cursrow, SP->_curscol));
198#if USE_WIDEC_SUPPORT
199    /*
200     * If this is not a valid character, there is nothing more to do.
201     */
202    if (isWidecExt(CHDEREF(ch))) {
203	TR(TRACE_CHARPUT, ("...skip"));
204	return;
205    }
206    /*
207     * Determine the number of character cells which the 'ch' value will use
208     * on the screen.  It should be at least one.
209     */
210    if ((chlen = wcwidth(CharOf(CHDEREF(ch)))) <= 0) {
211	static const NCURSES_CH_T blank = NewChar(BLANK_TEXT);
212
213	/*
214	 * If the character falls into any of these special cases, do
215	 * not force the result to a blank:
216	 *
217	 * a) it is printable (this works around a bug in wcwidth()).
218	 * b) use_legacy_coding() has been called to modify the treatment
219	 *    of codes 128-255.
220	 * c) the acs_map[] has been initialized to allow codes 0-31
221	 *    to be rendered.  This supports Linux console's "PC"
222	 *    characters.  Codes 128-255 are allowed though this is
223	 *    not checked.
224	 */
225	if (is8bits(CharOf(CHDEREF(ch)))
226	    && (isprint(CharOf(CHDEREF(ch)))
227		|| (SP->_legacy_coding > 0 && CharOf(CHDEREF(ch)) >= 160)
228		|| (SP->_legacy_coding > 1 && CharOf(CHDEREF(ch)) >= 128)
229		|| (AttrOf(attr) & A_ALTCHARSET
230		    && ((CharOfD(ch) < ACS_LEN
231			 && SP->_acs_map != 0
232			 && SP->_acs_map[CharOfD(ch)] != 0)
233			|| (CharOfD(ch) >= 128))))) {
234	    ;
235	} else {
236	    ch = CHREF(blank);
237	    TR(TRACE_CHARPUT, ("forced to blank"));
238	}
239	chlen = 1;
240    }
241#endif
242
243    if ((AttrOf(attr) & A_ALTCHARSET)
244	&& SP->_acs_map != 0
245	&& CharOfD(ch) < ACS_LEN) {
246	my_ch = CHDEREF(ch);	/* work around const param */
247#if USE_WIDEC_SUPPORT
248	/*
249	 * This is crude & ugly, but works most of the time.  It checks if the
250	 * acs_chars string specified that we have a mapping for this
251	 * character, and uses the wide-character mapping when we expect the
252	 * normal one to be broken (by mis-design ;-).
253	 */
254	if (SP->_screen_acs_fix
255	    && SP->_screen_acs_map[CharOf(my_ch)]) {
256	    RemAttr(attr, A_ALTCHARSET);
257	    my_ch = _nc_wacs[CharOf(my_ch)];
258	}
259#endif
260	/*
261	 * If we (still) have alternate character set, it is the normal 8bit
262	 * flavor.  The _screen_acs_map[] array tells if the character was
263	 * really in acs_chars, needed because of the way wide/normal line
264	 * drawing flavors are integrated.
265	 */
266	if (AttrOf(attr) & A_ALTCHARSET) {
267	    int j = CharOfD(ch);
268	    chtype temp = UChar(SP->_acs_map[j]);
269
270	    if (!(SP->_screen_acs_map[j])) {
271		RemAttr(attr, A_ALTCHARSET);
272		if (temp == 0)
273		    temp = ' ';
274	    }
275	    if (temp != 0)
276		SetChar(my_ch, temp, AttrOf(attr));
277	}
278	ch = CHREF(my_ch);
279    }
280    if (tilde_glitch && (CharOfD(ch) == L('~'))) {
281	SetChar(tilde, L('`'), AttrOf(attr));
282	ch = CHREF(tilde);
283    }
284
285    UpdateAttrs(attr);
286#if !USE_WIDEC_SUPPORT
287    /* FIXME - we do this special case for signal handling, should see how to
288     * make it work for wide characters.
289     */
290    if (SP->_outch != 0) {
291	SP->_outch(UChar(ch));
292    } else
293#endif
294    {
295	PUTC(CHDEREF(ch), SP->_ofp);	/* macro's fastest... */
296	COUNT_OUTCHARS(1);
297    }
298    SP->_curscol += chlen;
299    if (char_padding) {
300	TPUTS_TRACE("char_padding");
301	putp(char_padding);
302    }
303}
304
305static bool
306check_pending(void)
307/* check for pending input */
308{
309    bool have_pending = FALSE;
310
311    /*
312     * Only carry out this check when the flag is zero, otherwise we'll
313     * have the refreshing slow down drastically (or stop) if there's an
314     * unread character available.
315     */
316    if (SP->_fifohold != 0)
317	return FALSE;
318
319    if (SP->_checkfd >= 0) {
320#if USE_FUNC_POLL
321	struct pollfd fds[1];
322	fds[0].fd = SP->_checkfd;
323	fds[0].events = POLLIN;
324	if (poll(fds, 1, 0) > 0) {
325	    have_pending = TRUE;
326	}
327#elif defined(__BEOS__)
328	/*
329	 * BeOS's select() is declared in socket.h, so the configure script does
330	 * not see it.  That's just as well, since that function works only for
331	 * sockets.  This (using snooze and ioctl) was distilled from Be's patch
332	 * for ncurses which uses a separate thread to simulate select().
333	 *
334	 * FIXME: the return values from the ioctl aren't very clear if we get
335	 * interrupted.
336	 */
337	int n = 0;
338	int howmany = ioctl(0, 'ichr', &n);
339	if (howmany >= 0 && n > 0) {
340	    have_pending = TRUE;
341	}
342#elif HAVE_SELECT
343	fd_set fdset;
344	struct timeval ktimeout;
345
346	ktimeout.tv_sec =
347	    ktimeout.tv_usec = 0;
348
349	FD_ZERO(&fdset);
350	FD_SET(SP->_checkfd, &fdset);
351	if (select(SP->_checkfd + 1, &fdset, NULL, NULL, &ktimeout) != 0) {
352	    have_pending = TRUE;
353	}
354#endif
355    }
356    if (have_pending) {
357	SP->_fifohold = 5;
358	_nc_flush();
359    }
360    return FALSE;
361}
362
363/* put char at lower right corner */
364static void
365PutCharLR(const ARG_CH_T ch)
366{
367    if (!auto_right_margin) {
368	/* we can put the char directly */
369	PutAttrChar(ch);
370    } else if (enter_am_mode && exit_am_mode) {
371	/* we can suppress automargin */
372	TPUTS_TRACE("exit_am_mode");
373	putp(exit_am_mode);
374
375	PutAttrChar(ch);
376	SP->_curscol--;
377	position_check(SP->_cursrow, SP->_curscol, "exit_am_mode");
378
379	TPUTS_TRACE("enter_am_mode");
380	putp(enter_am_mode);
381    } else if ((enter_insert_mode && exit_insert_mode)
382	       || insert_character || parm_ich) {
383	GoTo(screen_lines - 1, screen_columns - 2);
384	PutAttrChar(ch);
385	GoTo(screen_lines - 1, screen_columns - 2);
386	InsStr(newscr->_line[screen_lines - 1].text + screen_columns - 2, 1);
387    }
388}
389
390/*
391 * Wrap the cursor position, i.e., advance to the beginning of the next line.
392 */
393static void
394wrap_cursor(void)
395{
396    if (eat_newline_glitch) {
397	/*
398	 * xenl can manifest two different ways.  The vt100 way is that, when
399	 * you'd expect the cursor to wrap, it stays hung at the right margin
400	 * (on top of the character just emitted) and doesn't wrap until the
401	 * *next* graphic char is emitted.  The c100 way is to ignore LF
402	 * received just after an am wrap.
403	 *
404	 * An aggressive way to handle this would be to emit CR/LF after the
405	 * char and then assume the wrap is done, you're on the first position
406	 * of the next line, and the terminal out of its weird state.  Here
407	 * it's safe to just tell the code that the cursor is in hyperspace and
408	 * let the next mvcur() call straighten things out.
409	 */
410	SP->_curscol = -1;
411	SP->_cursrow = -1;
412    } else if (auto_right_margin) {
413	SP->_curscol = 0;
414	SP->_cursrow++;
415	/*
416	 * We've actually moved - but may have to work around problems with
417	 * video attributes not working.
418	 */
419	if (!move_standout_mode && AttrOf(SCREEN_ATTRS(SP))) {
420	    TR(TRACE_CHARPUT, ("turning off (%#lx) %s before wrapping",
421			       (unsigned long) AttrOf(SCREEN_ATTRS(SP)),
422			       _traceattr(AttrOf(SCREEN_ATTRS(SP)))));
423	    (void) VIDATTR(A_NORMAL, 0);
424	}
425    } else {
426	SP->_curscol--;
427    }
428    position_check(SP->_cursrow, SP->_curscol, "wrap_cursor");
429}
430
431static NCURSES_INLINE void
432PutChar(const ARG_CH_T ch)
433/* insert character, handling automargin stuff */
434{
435    if (SP->_cursrow == screen_lines - 1 && SP->_curscol == screen_columns - 1)
436	PutCharLR(ch);
437    else
438	PutAttrChar(ch);
439
440    if (SP->_curscol >= screen_columns)
441	wrap_cursor();
442
443    position_check(SP->_cursrow, SP->_curscol, "PutChar");
444}
445
446/*
447 * Check whether the given character can be output by clearing commands.  This
448 * includes test for being a space and not including any 'bad' attributes, such
449 * as A_REVERSE.  All attribute flags which don't affect appearance of a space
450 * or can be output by clearing (A_COLOR in case of bce-terminal) are excluded.
451 */
452static NCURSES_INLINE bool
453can_clear_with(ARG_CH_T ch)
454{
455    if (!back_color_erase && SP->_coloron) {
456#if NCURSES_EXT_FUNCS
457	int pair;
458
459	if (!SP->_default_color)
460	    return FALSE;
461	if (SP->_default_fg != C_MASK || SP->_default_bg != C_MASK)
462	    return FALSE;
463	if ((pair = GetPair(CHDEREF(ch))) != 0) {
464	    short fg, bg;
465	    pair_content(pair, &fg, &bg);
466	    if (fg != C_MASK || bg != C_MASK)
467		return FALSE;
468	}
469#else
470	if (AttrOfD(ch) & A_COLOR)
471	    return FALSE;
472#endif
473    }
474    return (ISBLANK(CHDEREF(ch)) &&
475	    (AttrOfD(ch) & ~(NONBLANK_ATTR | A_COLOR)) == BLANK_ATTR);
476}
477
478/*
479 * Issue a given span of characters from an array.
480 * Must be functionally equivalent to:
481 *	for (i = 0; i < num; i++)
482 *	    PutChar(ntext[i]);
483 * but can leave the cursor positioned at the middle of the interval.
484 *
485 * Returns: 0 - cursor is at the end of interval
486 *	    1 - cursor is somewhere in the middle
487 *
488 * This code is optimized using ech and rep.
489 */
490static int
491EmitRange(const NCURSES_CH_T * ntext, int num)
492{
493    int i;
494
495    TR(TRACE_CHARPUT, ("EmitRange %d:%s", num, _nc_viscbuf(ntext, num)));
496
497    if (erase_chars || repeat_char) {
498	while (num > 0) {
499	    int runcount;
500	    NCURSES_CH_T ntext0;
501
502	    while (num > 1 && !CharEq(ntext[0], ntext[1])) {
503		PutChar(CHREF(ntext[0]));
504		ntext++;
505		num--;
506	    }
507	    ntext0 = ntext[0];
508	    if (num == 1) {
509		PutChar(CHREF(ntext0));
510		return 0;
511	    }
512	    runcount = 2;
513
514	    while (runcount < num && CharEq(ntext[runcount], ntext0))
515		runcount++;
516
517	    /*
518	     * The cost expression in the middle isn't exactly right.
519	     * _cup_ch_cost is an upper bound on the cost for moving to the
520	     * end of the erased area, but not the cost itself (which we
521	     * can't compute without emitting the move).  This may result
522	     * in erase_chars not getting used in some situations for
523	     * which it would be marginally advantageous.
524	     */
525	    if (erase_chars
526		&& runcount > SP->_ech_cost + SP->_cup_ch_cost
527		&& can_clear_with(CHREF(ntext0))) {
528		UpdateAttrs(ntext0);
529		putp(TPARM_1(erase_chars, runcount));
530
531		/*
532		 * If this is the last part of the given interval,
533		 * don't bother moving cursor, since it can be the
534		 * last update on the line.
535		 */
536		if (runcount < num) {
537		    GoTo(SP->_cursrow, SP->_curscol + runcount);
538		} else {
539		    return 1;	/* cursor stays in the middle */
540		}
541	    } else if (repeat_char && runcount > SP->_rep_cost) {
542		bool wrap_possible = (SP->_curscol + runcount >= screen_columns);
543		int rep_count = runcount;
544
545		if (wrap_possible)
546		    rep_count--;
547
548		UpdateAttrs(ntext0);
549		tputs(TPARM_2(repeat_char, CharOf(ntext0), rep_count),
550		      rep_count, _nc_outch);
551		SP->_curscol += rep_count;
552
553		if (wrap_possible)
554		    PutChar(CHREF(ntext0));
555	    } else {
556		for (i = 0; i < runcount; i++)
557		    PutChar(CHREF(ntext[i]));
558	    }
559	    ntext += runcount;
560	    num -= runcount;
561	}
562	return 0;
563    }
564
565    for (i = 0; i < num; i++)
566	PutChar(CHREF(ntext[i]));
567    return 0;
568}
569
570/*
571 * Output the line in the given range [first .. last]
572 *
573 * If there's a run of identical characters that's long enough to justify
574 * cursor movement, use that also.
575 *
576 * Returns: same as EmitRange
577 */
578static int
579PutRange(const NCURSES_CH_T * otext,
580	 const NCURSES_CH_T * ntext,
581	 int row,
582	 int first, int last)
583{
584    int i, j, same;
585
586    TR(TRACE_CHARPUT, ("PutRange(%p, %p, %d, %d, %d)",
587		       otext, ntext, row, first, last));
588
589    if (otext != ntext
590	&& (last - first + 1) > SP->_inline_cost) {
591	for (j = first, same = 0; j <= last; j++) {
592	    if (!same && isWidecExt(otext[j]))
593		continue;
594	    if (CharEq(otext[j], ntext[j])) {
595		same++;
596	    } else {
597		if (same > SP->_inline_cost) {
598		    EmitRange(ntext + first, j - same - first);
599		    GoTo(row, first = j);
600		}
601		same = 0;
602	    }
603	}
604	i = EmitRange(ntext + first, j - same - first);
605	/*
606	 * Always return 1 for the next GoTo() after a PutRange() if we found
607	 * identical characters at end of interval
608	 */
609	return (same == 0 ? i : 1);
610    }
611    return EmitRange(ntext + first, last - first + 1);
612}
613
614/* leave unbracketed here so 'indent' works */
615#define MARK_NOCHANGE(win,row) \
616		win->_line[row].firstchar = _NOCHANGE; \
617		win->_line[row].lastchar = _NOCHANGE; \
618		if_USE_SCROLL_HINTS(win->_line[row].oldindex = row)
619
620NCURSES_EXPORT(int)
621doupdate(void)
622{
623    int i;
624    int nonempty;
625#if USE_TRACE_TIMES
626    struct tms before, after;
627#endif /* USE_TRACE_TIMES */
628
629    T((T_CALLED("doupdate()")));
630
631    if (curscr == 0
632	|| newscr == 0)
633	returnCode(ERR);
634
635#ifdef TRACE
636    if (USE_TRACEF(TRACE_UPDATE)) {
637	if (curscr->_clear)
638	    _tracef("curscr is clear");
639	else
640	    _tracedump("curscr", curscr);
641	_tracedump("newscr", newscr);
642	_nc_unlock_global(tracef);
643    }
644#endif /* TRACE */
645
646    _nc_signal_handler(FALSE);
647
648    if (SP->_fifohold)
649	SP->_fifohold--;
650
651#if USE_SIZECHANGE
652    if (SP->_endwin || _nc_handle_sigwinch(SP)) {
653	/*
654	 * This is a transparent extension:  XSI does not address it,
655	 * and applications need not know that ncurses can do it.
656	 *
657	 * Check if the terminal size has changed while curses was off
658	 * (this can happen in an xterm, for example), and resize the
659	 * ncurses data structures accordingly.
660	 */
661	_nc_update_screensize(SP);
662    }
663#endif
664
665    if (SP->_endwin) {
666
667	T(("coming back from shell mode"));
668	reset_prog_mode();
669
670	_nc_mvcur_resume();
671	_nc_screen_resume();
672	SP->_mouse_resume(SP);
673
674	SP->_endwin = FALSE;
675    }
676#if USE_TRACE_TIMES
677    /* zero the metering machinery */
678    RESET_OUTCHARS();
679    (void) times(&before);
680#endif /* USE_TRACE_TIMES */
681
682    /*
683     * This is the support for magic-cookie terminals.  The theory:  we scan
684     * the virtual screen looking for attribute turnons.  Where we find one,
685     * check to make sure it's realizable by seeing if the required number of
686     * un-attributed blanks are present before and after the attributed range;
687     * try to shift the range boundaries over blanks (not changing the screen
688     * display) so this becomes true.  If it is, shift the beginning attribute
689     * change appropriately (the end one, if we've gotten this far, is
690     * guaranteed room for its cookie).  If not, nuke the added attributes out
691     * of the span.
692     */
693#if USE_XMC_SUPPORT
694    if (magic_cookie_glitch > 0) {
695	int j, k;
696	attr_t rattr = A_NORMAL;
697
698	for (i = 0; i < screen_lines; i++) {
699	    for (j = 0; j < screen_columns; j++) {
700		bool failed = FALSE;
701		NCURSES_CH_T *thisline = newscr->_line[i].text;
702		attr_t thisattr = AttrOf(thisline[j]) & SP->_xmc_triggers;
703		attr_t turnon = thisattr & ~rattr;
704
705		/* is an attribute turned on here? */
706		if (turnon == 0) {
707		    rattr = thisattr;
708		    continue;
709		}
710
711		TR(TRACE_ATTRS, ("At (%d, %d): from %s...", i, j, _traceattr(rattr)));
712		TR(TRACE_ATTRS, ("...to %s", _traceattr(turnon)));
713
714		/*
715		 * If the attribute change location is a blank with a "safe"
716		 * attribute, undo the attribute turnon.  This may ensure
717		 * there's enough room to set the attribute before the first
718		 * non-blank in the run.
719		 */
720#define SAFE(a)	(!((a) & SP->_xmc_triggers))
721		if (ISBLANK(thisline[j]) && SAFE(turnon)) {
722		    RemAttr(thisline[j], turnon);
723		    continue;
724		}
725
726		/* check that there's enough room at start of span */
727		for (k = 1; k <= magic_cookie_glitch; k++) {
728		    if (j - k < 0
729			|| !ISBLANK(thisline[j - k])
730			|| !SAFE(AttrOf(thisline[j - k]))) {
731			failed = TRUE;
732			TR(TRACE_ATTRS, ("No room at start in %d,%d%s%s",
733					 i, j - k,
734					 (ISBLANK(thisline[j - k])
735					  ? ""
736					  : ":nonblank"),
737					 (SAFE(AttrOf(thisline[j - k]))
738					  ? ""
739					  : ":unsafe")));
740			break;
741		    }
742		}
743		if (!failed) {
744		    bool end_onscreen = FALSE;
745		    int m, n = j;
746
747		    /* find end of span, if it's onscreen */
748		    for (m = i; m < screen_lines; m++) {
749			for (; n < screen_columns; n++) {
750			    attr_t testattr = AttrOf(newscr->_line[m].text[n]);
751			    if ((testattr & SP->_xmc_triggers) == rattr) {
752				end_onscreen = TRUE;
753				TR(TRACE_ATTRS,
754				   ("Range attributed with %s ends at (%d, %d)",
755				    _traceattr(turnon), m, n));
756				goto foundit;
757			    }
758			}
759			n = 0;
760		    }
761		    TR(TRACE_ATTRS,
762		       ("Range attributed with %s ends offscreen",
763			_traceattr(turnon)));
764		  foundit:;
765
766		    if (end_onscreen) {
767			NCURSES_CH_T *lastline = newscr->_line[m].text;
768
769			/*
770			 * If there are safely-attributed blanks at the end of
771			 * the range, shorten the range.  This will help ensure
772			 * that there is enough room at end of span.
773			 */
774			while (n >= 0
775			       && ISBLANK(lastline[n])
776			       && SAFE(AttrOf(lastline[n]))) {
777			    RemAttr(lastline[n--], turnon);
778			}
779
780			/* check that there's enough room at end of span */
781			for (k = 1; k <= magic_cookie_glitch; k++) {
782			    if (n + k >= screen_columns
783				|| !ISBLANK(lastline[n + k])
784				|| !SAFE(AttrOf(lastline[n + k]))) {
785				failed = TRUE;
786				TR(TRACE_ATTRS,
787				   ("No room at end in %d,%d%s%s",
788				    i, j - k,
789				    (ISBLANK(lastline[n + k])
790				     ? ""
791				     : ":nonblank"),
792				    (SAFE(AttrOf(lastline[n + k]))
793				     ? ""
794				     : ":unsafe")));
795				break;
796			    }
797			}
798		    }
799		}
800
801		if (failed) {
802		    int p, q = j;
803
804		    TR(TRACE_ATTRS,
805		       ("Clearing %s beginning at (%d, %d)",
806			_traceattr(turnon), i, j));
807
808		    /* turn off new attributes over span */
809		    for (p = i; p < screen_lines; p++) {
810			for (; q < screen_columns; q++) {
811			    attr_t testattr = AttrOf(newscr->_line[p].text[q]);
812			    if ((testattr & SP->_xmc_triggers) == rattr)
813				goto foundend;
814			    RemAttr(newscr->_line[p].text[q], turnon);
815			}
816			q = 0;
817		    }
818		  foundend:;
819		} else {
820		    TR(TRACE_ATTRS,
821		       ("Cookie space for %s found before (%d, %d)",
822			_traceattr(turnon), i, j));
823
824		    /*
825		     * Back up the start of range so there's room for cookies
826		     * before the first nonblank character.
827		     */
828		    for (k = 1; k <= magic_cookie_glitch; k++)
829			AddAttr(thisline[j - k], turnon);
830		}
831
832		rattr = thisattr;
833	    }
834	}
835
836#ifdef TRACE
837	/* show altered highlights after magic-cookie check */
838	if (USE_TRACEF(TRACE_UPDATE)) {
839	    _tracef("After magic-cookie check...");
840	    _tracedump("newscr", newscr);
841	    _nc_unlock_global(tracef);
842	}
843#endif /* TRACE */
844    }
845#endif /* USE_XMC_SUPPORT */
846
847    nonempty = 0;
848    if (curscr->_clear || newscr->_clear) {	/* force refresh ? */
849	ClrUpdate();
850	curscr->_clear = FALSE;	/* reset flag */
851	newscr->_clear = FALSE;	/* reset flag */
852    } else {
853	int changedlines = CHECK_INTERVAL;
854
855	if (check_pending())
856	    goto cleanup;
857
858	nonempty = min(screen_lines, newscr->_maxy + 1);
859
860	if (SP->_scrolling) {
861	    _nc_scroll_optimize();
862	}
863
864	nonempty = ClrBottom(nonempty);
865
866	TR(TRACE_UPDATE, ("Transforming lines, nonempty %d", nonempty));
867	for (i = 0; i < nonempty; i++) {
868	    /*
869	     * Here is our line-breakout optimization.
870	     */
871	    if (changedlines == CHECK_INTERVAL) {
872		if (check_pending())
873		    goto cleanup;
874		changedlines = 0;
875	    }
876
877	    /*
878	     * newscr->line[i].firstchar is normally set
879	     * by wnoutrefresh.  curscr->line[i].firstchar
880	     * is normally set by _nc_scroll_window in the
881	     * vertical-movement optimization code,
882	     */
883	    if (newscr->_line[i].firstchar != _NOCHANGE
884		|| curscr->_line[i].firstchar != _NOCHANGE) {
885		TransformLine(i);
886		changedlines++;
887	    }
888
889	    /* mark line changed successfully */
890	    if (i <= newscr->_maxy) {
891		MARK_NOCHANGE(newscr, i);
892	    }
893	    if (i <= curscr->_maxy) {
894		MARK_NOCHANGE(curscr, i);
895	    }
896	}
897    }
898
899    /* put everything back in sync */
900    for (i = nonempty; i <= newscr->_maxy; i++) {
901	MARK_NOCHANGE(newscr, i);
902    }
903    for (i = nonempty; i <= curscr->_maxy; i++) {
904	MARK_NOCHANGE(curscr, i);
905    }
906
907    if (!newscr->_leaveok) {
908	curscr->_curx = newscr->_curx;
909	curscr->_cury = newscr->_cury;
910
911	GoTo(curscr->_cury, curscr->_curx);
912    }
913
914  cleanup:
915    /*
916     * We would like to keep the physical screen in normal mode in case we get
917     * other processes writing to the screen.  This goal cannot be met for
918     * magic cookies since it interferes with attributes that may propagate
919     * past the current position.
920     */
921#if USE_XMC_SUPPORT
922    if (magic_cookie_glitch != 0)
923#endif
924	UpdateAttrs(normal);
925
926    _nc_flush();
927    WINDOW_ATTRS(curscr) = WINDOW_ATTRS(newscr);
928
929#if USE_TRACE_TIMES
930    (void) times(&after);
931    TR(TRACE_TIMES,
932       ("Update cost: %ld chars, %ld clocks system time, %ld clocks user time",
933	_nc_outchars,
934	(long) (after.tms_stime - before.tms_stime),
935	(long) (after.tms_utime - before.tms_utime)));
936#endif /* USE_TRACE_TIMES */
937
938    _nc_signal_handler(TRUE);
939
940    returnCode(OK);
941}
942
943/*
944 *	ClrBlank(win)
945 *
946 *	Returns the attributed character that corresponds to the "cleared"
947 *	screen.  If the terminal has the back-color-erase feature, this will be
948 *	colored according to the wbkgd() call.
949 *
950 *	We treat 'curscr' specially because it isn't supposed to be set directly
951 *	in the wbkgd() call.  Assume 'stdscr' for this case.
952 */
953#define BCE_ATTRS (A_NORMAL|A_COLOR)
954#define BCE_BKGD(win) (((win) == curscr ? stdscr : (win))->_nc_bkgd)
955
956static NCURSES_INLINE NCURSES_CH_T
957ClrBlank(WINDOW *win)
958{
959    NCURSES_CH_T blank = blankchar;
960    if (back_color_erase)
961	AddAttr(blank, (AttrOf(BCE_BKGD(win)) & BCE_ATTRS));
962    return blank;
963}
964
965/*
966**	ClrUpdate()
967**
968**	Update by clearing and redrawing the entire screen.
969**
970*/
971
972static void
973ClrUpdate(void)
974{
975    int i;
976    NCURSES_CH_T blank = ClrBlank(stdscr);
977    int nonempty = min(screen_lines, newscr->_maxy + 1);
978
979    TR(TRACE_UPDATE, (T_CALLED("ClrUpdate")));
980
981    ClearScreen(blank);
982
983    TR(TRACE_UPDATE, ("updating screen from scratch"));
984
985    nonempty = ClrBottom(nonempty);
986
987    for (i = 0; i < nonempty; i++)
988	TransformLine(i);
989
990    TR(TRACE_UPDATE, (T_RETURN("")));
991}
992
993/*
994**	ClrToEOL(blank)
995**
996**	Clear to end of current line, starting at the cursor position
997*/
998
999static void
1000ClrToEOL(NCURSES_CH_T blank, bool needclear)
1001{
1002    int j;
1003
1004    if (curscr != 0
1005	&& SP->_cursrow >= 0) {
1006	for (j = SP->_curscol; j < screen_columns; j++) {
1007	    if (j >= 0) {
1008		NCURSES_CH_T *cp = &(curscr->_line[SP->_cursrow].text[j]);
1009
1010		if (!CharEq(*cp, blank)) {
1011		    *cp = blank;
1012		    needclear = TRUE;
1013		}
1014	    }
1015	}
1016    } else {
1017	needclear = TRUE;
1018    }
1019
1020    if (needclear) {
1021	UpdateAttrs(blank);
1022	TPUTS_TRACE("clr_eol");
1023	if (clr_eol && SP->_el_cost <= (screen_columns - SP->_curscol)) {
1024	    putp(clr_eol);
1025	} else {
1026	    int count = (screen_columns - SP->_curscol);
1027	    while (count-- > 0)
1028		PutChar(CHREF(blank));
1029	}
1030    }
1031}
1032
1033/*
1034**	ClrToEOS(blank)
1035**
1036**	Clear to end of screen, starting at the cursor position
1037*/
1038
1039static void
1040ClrToEOS(NCURSES_CH_T blank)
1041{
1042    int row, col;
1043
1044    row = SP->_cursrow;
1045    col = SP->_curscol;
1046
1047    UpdateAttrs(blank);
1048    TPUTS_TRACE("clr_eos");
1049    tputs(clr_eos, screen_lines - row, _nc_outch);
1050
1051    while (col < screen_columns)
1052	curscr->_line[row].text[col++] = blank;
1053
1054    for (row++; row < screen_lines; row++) {
1055	for (col = 0; col < screen_columns; col++)
1056	    curscr->_line[row].text[col] = blank;
1057    }
1058}
1059
1060/*
1061 *	ClrBottom(total)
1062 *
1063 *	Test if clearing the end of the screen would satisfy part of the
1064 *	screen-update.  Do this by scanning backwards through the lines in the
1065 *	screen, checking if each is blank, and one or more are changed.
1066 */
1067static int
1068ClrBottom(int total)
1069{
1070    int row;
1071    int col;
1072    int top = total;
1073    int last = min(screen_columns, newscr->_maxx + 1);
1074    NCURSES_CH_T blank = newscr->_line[total - 1].text[last - 1];
1075    bool ok;
1076
1077    if (clr_eos && can_clear_with(CHREF(blank))) {
1078
1079	for (row = total - 1; row >= 0; row--) {
1080	    for (col = 0, ok = TRUE; ok && col < last; col++) {
1081		ok = (CharEq(newscr->_line[row].text[col], blank));
1082	    }
1083	    if (!ok)
1084		break;
1085
1086	    for (col = 0; ok && col < last; col++) {
1087		ok = (CharEq(curscr->_line[row].text[col], blank));
1088	    }
1089	    if (!ok)
1090		top = row;
1091	}
1092
1093	/* don't use clr_eos for just one line if clr_eol available */
1094	if (top < total) {
1095	    GoTo(top, 0);
1096	    ClrToEOS(blank);
1097	    if (SP->oldhash && SP->newhash) {
1098		for (row = top; row < screen_lines; row++)
1099		    SP->oldhash[row] = SP->newhash[row];
1100	    }
1101	}
1102    }
1103    return top;
1104}
1105
1106#if USE_XMC_SUPPORT
1107#if USE_WIDEC_SUPPORT
1108#define check_xmc_transition(a, b) \
1109    ((((a)->attr ^ (b)->attr) & ~((a)->attr) & SP->_xmc_triggers) != 0)
1110#define xmc_turn_on(a,b) check_xmc_transition(&(a), &(b))
1111#else
1112#define xmc_turn_on(a,b) ((((a)^(b)) & ~(a) & SP->_xmc_triggers) != 0)
1113#endif
1114
1115#define xmc_new(r,c) newscr->_line[r].text[c]
1116#define xmc_turn_off(a,b) xmc_turn_on(b,a)
1117#endif /* USE_XMC_SUPPORT */
1118
1119/*
1120**	TransformLine(lineno)
1121**
1122**	Transform the given line in curscr to the one in newscr, using
1123**	Insert/Delete Character if _nc_idcok && has_ic().
1124**
1125**		firstChar = position of first different character in line
1126**		oLastChar = position of last different character in old line
1127**		nLastChar = position of last different character in new line
1128**
1129**		move to firstChar
1130**		overwrite chars up to min(oLastChar, nLastChar)
1131**		if oLastChar < nLastChar
1132**			insert newLine[oLastChar+1..nLastChar]
1133**		else
1134**			delete oLastChar - nLastChar spaces
1135*/
1136
1137static void
1138TransformLine(int const lineno)
1139{
1140    int firstChar, oLastChar, nLastChar;
1141    NCURSES_CH_T *newLine = newscr->_line[lineno].text;
1142    NCURSES_CH_T *oldLine = curscr->_line[lineno].text;
1143    int n;
1144    bool attrchanged = FALSE;
1145
1146    TR(TRACE_UPDATE, (T_CALLED("TransformLine(%d)"), lineno));
1147
1148    /* copy new hash value to old one */
1149    if (SP->oldhash && SP->newhash)
1150	SP->oldhash[lineno] = SP->newhash[lineno];
1151
1152    /*
1153     * If we have colors, there is the possibility of having two color pairs
1154     * that display as the same colors.  For instance, Lynx does this.  Check
1155     * for this case, and update the old line with the new line's colors when
1156     * they are equivalent.
1157     */
1158    if (SP->_coloron) {
1159	int oldPair;
1160	int newPair;
1161
1162	for (n = 0; n < screen_columns; n++) {
1163	    if (!CharEq(newLine[n], oldLine[n])) {
1164		oldPair = GetPair(oldLine[n]);
1165		newPair = GetPair(newLine[n]);
1166		if (oldPair != newPair
1167		    && unColor(oldLine[n]) == unColor(newLine[n])) {
1168		    if (oldPair < COLOR_PAIRS
1169			&& newPair < COLOR_PAIRS
1170			&& SP->_color_pairs[oldPair] == SP->_color_pairs[newPair]) {
1171			SetPair(oldLine[n], GetPair(newLine[n]));
1172		    }
1173		}
1174	    }
1175	}
1176    }
1177
1178    if (ceol_standout_glitch && clr_eol) {
1179	firstChar = 0;
1180	while (firstChar < screen_columns) {
1181	    if (!SameAttrOf(newLine[firstChar], oldLine[firstChar])) {
1182		attrchanged = TRUE;
1183		break;
1184	    }
1185	    firstChar++;
1186	}
1187    }
1188
1189    firstChar = 0;
1190
1191    if (attrchanged) {		/* we may have to disregard the whole line */
1192	GoTo(lineno, firstChar);
1193	ClrToEOL(ClrBlank(curscr), FALSE);
1194	PutRange(oldLine, newLine, lineno, 0, (screen_columns - 1));
1195#if USE_XMC_SUPPORT
1196
1197	/*
1198	 * This is a very simple loop to paint characters which may have the
1199	 * magic cookie glitch embedded.  It doesn't know much about video
1200	 * attributes which are continued from one line to the next.  It
1201	 * assumes that we have filtered out requests for attribute changes
1202	 * that do not get mapped to blank positions.
1203	 *
1204	 * FIXME: we are not keeping track of where we put the cookies, so this
1205	 * will work properly only once, since we may overwrite a cookie in a
1206	 * following operation.
1207	 */
1208    } else if (magic_cookie_glitch > 0) {
1209	GoTo(lineno, firstChar);
1210	for (n = 0; n < screen_columns; n++) {
1211	    int m = n + magic_cookie_glitch;
1212
1213	    /* check for turn-on:
1214	     * If we are writing an attributed blank, where the
1215	     * previous cell is not attributed.
1216	     */
1217	    if (ISBLANK(newLine[n])
1218		&& ((n > 0
1219		     && xmc_turn_on(newLine[n - 1], newLine[n]))
1220		    || (n == 0
1221			&& lineno > 0
1222			&& xmc_turn_on(xmc_new(lineno - 1, screen_columns - 1),
1223				       newLine[n])))) {
1224		n = m;
1225	    }
1226
1227	    PutChar(CHREF(newLine[n]));
1228
1229	    /* check for turn-off:
1230	     * If we are writing an attributed non-blank, where the
1231	     * next cell is blank, and not attributed.
1232	     */
1233	    if (!ISBLANK(newLine[n])
1234		&& ((n + 1 < screen_columns
1235		     && xmc_turn_off(newLine[n], newLine[n + 1]))
1236		    || (n + 1 >= screen_columns
1237			&& lineno + 1 < screen_lines
1238			&& xmc_turn_off(newLine[n], xmc_new(lineno + 1, 0))))) {
1239		n = m;
1240	    }
1241
1242	}
1243#endif
1244    } else {
1245	NCURSES_CH_T blank;
1246
1247	/* it may be cheap to clear leading whitespace with clr_bol */
1248	blank = newLine[0];
1249	if (clr_bol && can_clear_with(CHREF(blank))) {
1250	    int oFirstChar, nFirstChar;
1251
1252	    for (oFirstChar = 0; oFirstChar < screen_columns; oFirstChar++)
1253		if (!CharEq(oldLine[oFirstChar], blank))
1254		    break;
1255	    for (nFirstChar = 0; nFirstChar < screen_columns; nFirstChar++)
1256		if (!CharEq(newLine[nFirstChar], blank))
1257		    break;
1258
1259	    if (nFirstChar == oFirstChar) {
1260		firstChar = nFirstChar;
1261		/* find the first differing character */
1262		while (firstChar < screen_columns
1263		       && CharEq(newLine[firstChar], oldLine[firstChar]))
1264		    firstChar++;
1265	    } else if (oFirstChar > nFirstChar) {
1266		firstChar = nFirstChar;
1267	    } else {		/* oFirstChar < nFirstChar */
1268		firstChar = oFirstChar;
1269		if (SP->_el1_cost < nFirstChar - oFirstChar) {
1270		    if (nFirstChar >= screen_columns
1271			&& SP->_el_cost <= SP->_el1_cost) {
1272			GoTo(lineno, 0);
1273			UpdateAttrs(blank);
1274			TPUTS_TRACE("clr_eol");
1275			putp(clr_eol);
1276		    } else {
1277			GoTo(lineno, nFirstChar - 1);
1278			UpdateAttrs(blank);
1279			TPUTS_TRACE("clr_bol");
1280			putp(clr_bol);
1281		    }
1282
1283		    while (firstChar < nFirstChar)
1284			oldLine[firstChar++] = blank;
1285		}
1286	    }
1287	} else {
1288	    /* find the first differing character */
1289	    while (firstChar < screen_columns
1290		   && CharEq(newLine[firstChar], oldLine[firstChar]))
1291		firstChar++;
1292	}
1293	/* if there wasn't one, we're done */
1294	if (firstChar >= screen_columns) {
1295	    TR(TRACE_UPDATE, (T_RETURN("")));
1296	    return;
1297	}
1298
1299	blank = newLine[screen_columns - 1];
1300
1301	if (!can_clear_with(CHREF(blank))) {
1302	    /* find the last differing character */
1303	    nLastChar = screen_columns - 1;
1304
1305	    while (nLastChar > firstChar
1306		   && CharEq(newLine[nLastChar], oldLine[nLastChar]))
1307		nLastChar--;
1308
1309	    if (nLastChar >= firstChar) {
1310		GoTo(lineno, firstChar);
1311		PutRange(oldLine, newLine, lineno, firstChar, nLastChar);
1312		memcpy(oldLine + firstChar,
1313		       newLine + firstChar,
1314		       (nLastChar - firstChar + 1) * sizeof(NCURSES_CH_T));
1315	    }
1316	    TR(TRACE_UPDATE, (T_RETURN("")));
1317	    return;
1318	}
1319
1320	/* find last non-blank character on old line */
1321	oLastChar = screen_columns - 1;
1322	while (oLastChar > firstChar && CharEq(oldLine[oLastChar], blank))
1323	    oLastChar--;
1324
1325	/* find last non-blank character on new line */
1326	nLastChar = screen_columns - 1;
1327	while (nLastChar > firstChar && CharEq(newLine[nLastChar], blank))
1328	    nLastChar--;
1329
1330	if ((nLastChar == firstChar)
1331	    && (SP->_el_cost < (oLastChar - nLastChar))) {
1332	    GoTo(lineno, firstChar);
1333	    if (!CharEq(newLine[firstChar], blank))
1334		PutChar(CHREF(newLine[firstChar]));
1335	    ClrToEOL(blank, FALSE);
1336	} else if ((nLastChar != oLastChar)
1337		   && (!CharEq(newLine[nLastChar], oldLine[oLastChar])
1338		       || !(_nc_idcok && has_ic()))) {
1339	    GoTo(lineno, firstChar);
1340	    if ((oLastChar - nLastChar) > SP->_el_cost) {
1341		if (PutRange(oldLine, newLine, lineno, firstChar, nLastChar))
1342		    GoTo(lineno, nLastChar + 1);
1343		ClrToEOL(blank, FALSE);
1344	    } else {
1345		n = max(nLastChar, oLastChar);
1346		PutRange(oldLine, newLine, lineno, firstChar, n);
1347	    }
1348	} else {
1349	    int nLastNonblank = nLastChar;
1350	    int oLastNonblank = oLastChar;
1351
1352	    /* find the last characters that really differ */
1353	    /* can be -1 if no characters differ */
1354	    while (CharEq(newLine[nLastChar], oldLine[oLastChar])) {
1355		/* don't split a wide char */
1356		if (isWidecExt(newLine[nLastChar]) &&
1357		    !CharEq(newLine[nLastChar - 1], oldLine[oLastChar - 1]))
1358		    break;
1359		nLastChar--;
1360		oLastChar--;
1361		if (nLastChar == -1 || oLastChar == -1)
1362		    break;
1363	    }
1364
1365	    n = min(oLastChar, nLastChar);
1366	    if (n >= firstChar) {
1367		GoTo(lineno, firstChar);
1368		PutRange(oldLine, newLine, lineno, firstChar, n);
1369	    }
1370
1371	    if (oLastChar < nLastChar) {
1372		int m = max(nLastNonblank, oLastNonblank);
1373#if USE_WIDEC_SUPPORT
1374		while (isWidecExt(newLine[n + 1]) && n) {
1375		    --n;
1376		    --oLastChar;
1377		}
1378#endif
1379		GoTo(lineno, n + 1);
1380		if ((nLastChar < nLastNonblank)
1381		    || InsCharCost(nLastChar - oLastChar) > (m - n)) {
1382		    PutRange(oldLine, newLine, lineno, n + 1, m);
1383		} else {
1384		    InsStr(&newLine[n + 1], nLastChar - oLastChar);
1385		}
1386	    } else if (oLastChar > nLastChar) {
1387		GoTo(lineno, n + 1);
1388		if (DelCharCost(oLastChar - nLastChar)
1389		    > SP->_el_cost + nLastNonblank - (n + 1)) {
1390		    if (PutRange(oldLine, newLine, lineno,
1391				 n + 1, nLastNonblank))
1392			GoTo(lineno, nLastNonblank + 1);
1393		    ClrToEOL(blank, FALSE);
1394		} else {
1395		    /*
1396		     * The delete-char sequence will
1397		     * effectively shift in blanks from the
1398		     * right margin of the screen.  Ensure
1399		     * that they are the right color by
1400		     * setting the video attributes from
1401		     * the last character on the row.
1402		     */
1403		    UpdateAttrs(blank);
1404		    DelChar(oLastChar - nLastChar);
1405		}
1406	    }
1407	}
1408    }
1409
1410    /* update the code's internal representation */
1411    if (screen_columns > firstChar)
1412	memcpy(oldLine + firstChar,
1413	       newLine + firstChar,
1414	       (screen_columns - firstChar) * sizeof(NCURSES_CH_T));
1415    TR(TRACE_UPDATE, (T_RETURN("")));
1416    return;
1417}
1418
1419/*
1420**	ClearScreen(blank)
1421**
1422**	Clear the physical screen and put cursor at home
1423**
1424*/
1425
1426static void
1427ClearScreen(NCURSES_CH_T blank)
1428{
1429    int i, j;
1430    bool fast_clear = (clear_screen || clr_eos || clr_eol);
1431
1432    TR(TRACE_UPDATE, ("ClearScreen() called"));
1433
1434#if NCURSES_EXT_FUNCS
1435    if (SP->_coloron
1436	&& !SP->_default_color) {
1437	_nc_do_color(GET_SCREEN_PAIR(SP), 0, FALSE, _nc_outch);
1438	if (!back_color_erase) {
1439	    fast_clear = FALSE;
1440	}
1441    }
1442#endif
1443
1444    if (fast_clear) {
1445	if (clear_screen) {
1446	    UpdateAttrs(blank);
1447	    TPUTS_TRACE("clear_screen");
1448	    putp(clear_screen);
1449	    SP->_cursrow = SP->_curscol = 0;
1450	    position_check(SP->_cursrow, SP->_curscol, "ClearScreen");
1451	} else if (clr_eos) {
1452	    SP->_cursrow = SP->_curscol = -1;
1453	    GoTo(0, 0);
1454
1455	    UpdateAttrs(blank);
1456	    TPUTS_TRACE("clr_eos");
1457	    tputs(clr_eos, screen_lines, _nc_outch);
1458	} else if (clr_eol) {
1459	    SP->_cursrow = SP->_curscol = -1;
1460
1461	    UpdateAttrs(blank);
1462	    for (i = 0; i < screen_lines; i++) {
1463		GoTo(i, 0);
1464		TPUTS_TRACE("clr_eol");
1465		putp(clr_eol);
1466	    }
1467	    GoTo(0, 0);
1468	}
1469    } else {
1470	UpdateAttrs(blank);
1471	for (i = 0; i < screen_lines; i++) {
1472	    GoTo(i, 0);
1473	    for (j = 0; j < screen_columns; j++)
1474		PutChar(CHREF(blank));
1475	}
1476	GoTo(0, 0);
1477    }
1478
1479    for (i = 0; i < screen_lines; i++) {
1480	for (j = 0; j < screen_columns; j++)
1481	    curscr->_line[i].text[j] = blank;
1482    }
1483
1484    TR(TRACE_UPDATE, ("screen cleared"));
1485}
1486
1487/*
1488**	InsStr(line, count)
1489**
1490**	Insert the count characters pointed to by line.
1491**
1492*/
1493
1494static void
1495InsStr(NCURSES_CH_T * line, int count)
1496{
1497    TR(TRACE_UPDATE, ("InsStr(%p,%d) called", line, count));
1498
1499    /* Prefer parm_ich as it has the smallest cost - no need to shift
1500     * the whole line on each character. */
1501    /* The order must match that of InsCharCost. */
1502    if (parm_ich) {
1503	TPUTS_TRACE("parm_ich");
1504	tputs(TPARM_1(parm_ich, count), count, _nc_outch);
1505	while (count) {
1506	    PutAttrChar(CHREF(*line));
1507	    line++;
1508	    count--;
1509	}
1510    } else if (enter_insert_mode && exit_insert_mode) {
1511	TPUTS_TRACE("enter_insert_mode");
1512	putp(enter_insert_mode);
1513	while (count) {
1514	    PutAttrChar(CHREF(*line));
1515	    if (insert_padding) {
1516		TPUTS_TRACE("insert_padding");
1517		putp(insert_padding);
1518	    }
1519	    line++;
1520	    count--;
1521	}
1522	TPUTS_TRACE("exit_insert_mode");
1523	putp(exit_insert_mode);
1524    } else {
1525	while (count) {
1526	    TPUTS_TRACE("insert_character");
1527	    putp(insert_character);
1528	    PutAttrChar(CHREF(*line));
1529	    if (insert_padding) {
1530		TPUTS_TRACE("insert_padding");
1531		putp(insert_padding);
1532	    }
1533	    line++;
1534	    count--;
1535	}
1536    }
1537    position_check(SP->_cursrow, SP->_curscol, "InsStr");
1538}
1539
1540/*
1541**	DelChar(count)
1542**
1543**	Delete count characters at current position
1544**
1545*/
1546
1547static void
1548DelChar(int count)
1549{
1550    int n;
1551
1552    TR(TRACE_UPDATE, ("DelChar(%d) called, position = (%ld,%ld)",
1553		      count,
1554		      (long) newscr->_cury,
1555		      (long) newscr->_curx));
1556
1557    if (parm_dch) {
1558	TPUTS_TRACE("parm_dch");
1559	tputs(TPARM_1(parm_dch, count), count, _nc_outch);
1560    } else {
1561	for (n = 0; n < count; n++) {
1562	    TPUTS_TRACE("delete_character");
1563	    putp(delete_character);
1564	}
1565    }
1566}
1567
1568/*
1569 * Physical-scrolling support
1570 *
1571 * This code was adapted from Keith Bostic's hardware scrolling
1572 * support for 4.4BSD curses.  I (esr) translated it to use terminfo
1573 * capabilities, narrowed the call interface slightly, and cleaned
1574 * up some convoluted tests.  I also added support for the memory_above
1575 * memory_below, and non_dest_scroll_region capabilities.
1576 *
1577 * For this code to work, we must have either
1578 * change_scroll_region and scroll forward/reverse commands, or
1579 * insert and delete line capabilities.
1580 * When the scrolling region has been set, the cursor has to
1581 * be at the last line of the region to make the scroll up
1582 * happen, or on the first line of region to scroll down.
1583 *
1584 * This code makes one aesthetic decision in the opposite way from
1585 * BSD curses.  BSD curses preferred pairs of il/dl operations
1586 * over scrolls, allegedly because il/dl looked faster.  We, on
1587 * the other hand, prefer scrolls because (a) they're just as fast
1588 * on many terminals and (b) using them avoids bouncing an
1589 * unchanged bottom section of the screen up and down, which is
1590 * visually nasty.
1591 *
1592 * (lav): added more cases, used dl/il when bot==maxy and in csr case.
1593 *
1594 * I used assumption that capabilities il/il1/dl/dl1 work inside
1595 * changed scroll region not shifting screen contents outside of it.
1596 * If there are any terminals behaving different way, it would be
1597 * necessary to add some conditions to scroll_csr_forward/backward.
1598 */
1599
1600/* Try to scroll up assuming given csr (miny, maxy). Returns ERR on failure */
1601static int
1602scroll_csr_forward(int n, int top, int bot, int miny, int maxy, NCURSES_CH_T blank)
1603{
1604    int i;
1605
1606    if (n == 1 && scroll_forward && top == miny && bot == maxy) {
1607	GoTo(bot, 0);
1608	UpdateAttrs(blank);
1609	TPUTS_TRACE("scroll_forward");
1610	putp(scroll_forward);
1611    } else if (n == 1 && delete_line && bot == maxy) {
1612	GoTo(top, 0);
1613	UpdateAttrs(blank);
1614	TPUTS_TRACE("delete_line");
1615	putp(delete_line);
1616    } else if (parm_index && top == miny && bot == maxy) {
1617	GoTo(bot, 0);
1618	UpdateAttrs(blank);
1619	TPUTS_TRACE("parm_index");
1620	tputs(TPARM_2(parm_index, n, 0), n, _nc_outch);
1621    } else if (parm_delete_line && bot == maxy) {
1622	GoTo(top, 0);
1623	UpdateAttrs(blank);
1624	TPUTS_TRACE("parm_delete_line");
1625	tputs(TPARM_2(parm_delete_line, n, 0), n, _nc_outch);
1626    } else if (scroll_forward && top == miny && bot == maxy) {
1627	GoTo(bot, 0);
1628	UpdateAttrs(blank);
1629	for (i = 0; i < n; i++) {
1630	    TPUTS_TRACE("scroll_forward");
1631	    putp(scroll_forward);
1632	}
1633    } else if (delete_line && bot == maxy) {
1634	GoTo(top, 0);
1635	UpdateAttrs(blank);
1636	for (i = 0; i < n; i++) {
1637	    TPUTS_TRACE("delete_line");
1638	    putp(delete_line);
1639	}
1640    } else
1641	return ERR;
1642
1643#if NCURSES_EXT_FUNCS
1644    if (FILL_BCE()) {
1645	int j;
1646	for (i = 0; i < n; i++) {
1647	    GoTo(bot - i, 0);
1648	    for (j = 0; j < screen_columns; j++)
1649		PutChar(CHREF(blank));
1650	}
1651    }
1652#endif
1653    return OK;
1654}
1655
1656/* Try to scroll down assuming given csr (miny, maxy). Returns ERR on failure */
1657/* n > 0 */
1658static int
1659scroll_csr_backward(int n, int top, int bot, int miny, int maxy,
1660		    NCURSES_CH_T blank)
1661{
1662    int i;
1663
1664    if (n == 1 && scroll_reverse && top == miny && bot == maxy) {
1665	GoTo(top, 0);
1666	UpdateAttrs(blank);
1667	TPUTS_TRACE("scroll_reverse");
1668	putp(scroll_reverse);
1669    } else if (n == 1 && insert_line && bot == maxy) {
1670	GoTo(top, 0);
1671	UpdateAttrs(blank);
1672	TPUTS_TRACE("insert_line");
1673	putp(insert_line);
1674    } else if (parm_rindex && top == miny && bot == maxy) {
1675	GoTo(top, 0);
1676	UpdateAttrs(blank);
1677	TPUTS_TRACE("parm_rindex");
1678	tputs(TPARM_2(parm_rindex, n, 0), n, _nc_outch);
1679    } else if (parm_insert_line && bot == maxy) {
1680	GoTo(top, 0);
1681	UpdateAttrs(blank);
1682	TPUTS_TRACE("parm_insert_line");
1683	tputs(TPARM_2(parm_insert_line, n, 0), n, _nc_outch);
1684    } else if (scroll_reverse && top == miny && bot == maxy) {
1685	GoTo(top, 0);
1686	UpdateAttrs(blank);
1687	for (i = 0; i < n; i++) {
1688	    TPUTS_TRACE("scroll_reverse");
1689	    putp(scroll_reverse);
1690	}
1691    } else if (insert_line && bot == maxy) {
1692	GoTo(top, 0);
1693	UpdateAttrs(blank);
1694	for (i = 0; i < n; i++) {
1695	    TPUTS_TRACE("insert_line");
1696	    putp(insert_line);
1697	}
1698    } else
1699	return ERR;
1700
1701#if NCURSES_EXT_FUNCS
1702    if (FILL_BCE()) {
1703	int j;
1704	for (i = 0; i < n; i++) {
1705	    GoTo(top + i, 0);
1706	    for (j = 0; j < screen_columns; j++)
1707		PutChar(CHREF(blank));
1708	}
1709    }
1710#endif
1711    return OK;
1712}
1713
1714/* scroll by using delete_line at del and insert_line at ins */
1715/* n > 0 */
1716static int
1717scroll_idl(int n, int del, int ins, NCURSES_CH_T blank)
1718{
1719    int i;
1720
1721    if (!((parm_delete_line || delete_line) && (parm_insert_line || insert_line)))
1722	return ERR;
1723
1724    GoTo(del, 0);
1725    UpdateAttrs(blank);
1726    if (n == 1 && delete_line) {
1727	TPUTS_TRACE("delete_line");
1728	putp(delete_line);
1729    } else if (parm_delete_line) {
1730	TPUTS_TRACE("parm_delete_line");
1731	tputs(TPARM_2(parm_delete_line, n, 0), n, _nc_outch);
1732    } else {			/* if (delete_line) */
1733	for (i = 0; i < n; i++) {
1734	    TPUTS_TRACE("delete_line");
1735	    putp(delete_line);
1736	}
1737    }
1738
1739    GoTo(ins, 0);
1740    UpdateAttrs(blank);
1741    if (n == 1 && insert_line) {
1742	TPUTS_TRACE("insert_line");
1743	putp(insert_line);
1744    } else if (parm_insert_line) {
1745	TPUTS_TRACE("parm_insert_line");
1746	tputs(TPARM_2(parm_insert_line, n, 0), n, _nc_outch);
1747    } else {			/* if (insert_line) */
1748	for (i = 0; i < n; i++) {
1749	    TPUTS_TRACE("insert_line");
1750	    putp(insert_line);
1751	}
1752    }
1753
1754    return OK;
1755}
1756
1757/*
1758 * Note:  some terminals require the cursor to be within the scrolling margins
1759 * before setting them.  Generally, the cursor must be at the appropriate end
1760 * of the scrolling margins when issuing an indexing operation (it is not
1761 * apparent whether it must also be at the left margin; we do this just to be
1762 * safe).  To make the related cursor movement a little faster, we use the
1763 * save/restore cursor capabilities if the terminal has them.
1764 */
1765NCURSES_EXPORT(int)
1766_nc_scrolln(int n, int top, int bot, int maxy)
1767/* scroll region from top to bot by n lines */
1768{
1769    NCURSES_CH_T blank = ClrBlank(stdscr);
1770    int i;
1771    bool cursor_saved = FALSE;
1772    int res;
1773
1774    TR(TRACE_MOVE, ("mvcur_scrolln(%d, %d, %d, %d)", n, top, bot, maxy));
1775
1776#if USE_XMC_SUPPORT
1777    /*
1778     * If we scroll, we might remove a cookie.
1779     */
1780    if (magic_cookie_glitch > 0) {
1781	return (ERR);
1782    }
1783#endif
1784
1785    if (n > 0) {		/* scroll up (forward) */
1786	/*
1787	 * Explicitly clear if stuff pushed off top of region might
1788	 * be saved by the terminal.
1789	 */
1790	res = scroll_csr_forward(n, top, bot, 0, maxy, blank);
1791
1792	if (res == ERR && change_scroll_region) {
1793	    if ((((n == 1 && scroll_forward) || parm_index)
1794		 && (SP->_cursrow == bot || SP->_cursrow == bot - 1))
1795		&& save_cursor && restore_cursor) {
1796		cursor_saved = TRUE;
1797		TPUTS_TRACE("save_cursor");
1798		putp(save_cursor);
1799	    }
1800	    TPUTS_TRACE("change_scroll_region");
1801	    putp(TPARM_2(change_scroll_region, top, bot));
1802	    if (cursor_saved) {
1803		TPUTS_TRACE("restore_cursor");
1804		putp(restore_cursor);
1805	    } else {
1806		SP->_cursrow = SP->_curscol = -1;
1807	    }
1808
1809	    res = scroll_csr_forward(n, top, bot, top, bot, blank);
1810
1811	    TPUTS_TRACE("change_scroll_region");
1812	    putp(TPARM_2(change_scroll_region, 0, maxy));
1813	    SP->_cursrow = SP->_curscol = -1;
1814	}
1815
1816	if (res == ERR && _nc_idlok)
1817	    res = scroll_idl(n, top, bot - n + 1, blank);
1818
1819	/*
1820	 * Clear the newly shifted-in text.
1821	 */
1822	if (res != ERR
1823	    && (non_dest_scroll_region || (memory_below && bot == maxy))) {
1824	    static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
1825	    if (bot == maxy && clr_eos) {
1826		GoTo(bot - n + 1, 0);
1827		ClrToEOS(blank2);
1828	    } else {
1829		for (i = 0; i < n; i++) {
1830		    GoTo(bot - i, 0);
1831		    ClrToEOL(blank2, FALSE);
1832		}
1833	    }
1834	}
1835
1836    } else {			/* (n < 0) - scroll down (backward) */
1837	res = scroll_csr_backward(-n, top, bot, 0, maxy, blank);
1838
1839	if (res == ERR && change_scroll_region) {
1840	    if (top != 0 && (SP->_cursrow == top || SP->_cursrow == top - 1)
1841		&& save_cursor && restore_cursor) {
1842		cursor_saved = TRUE;
1843		TPUTS_TRACE("save_cursor");
1844		putp(save_cursor);
1845	    }
1846	    TPUTS_TRACE("change_scroll_region");
1847	    putp(TPARM_2(change_scroll_region, top, bot));
1848	    if (cursor_saved) {
1849		TPUTS_TRACE("restore_cursor");
1850		putp(restore_cursor);
1851	    } else {
1852		SP->_cursrow = SP->_curscol = -1;
1853	    }
1854
1855	    res = scroll_csr_backward(-n, top, bot, top, bot, blank);
1856
1857	    TPUTS_TRACE("change_scroll_region");
1858	    putp(TPARM_2(change_scroll_region, 0, maxy));
1859	    SP->_cursrow = SP->_curscol = -1;
1860	}
1861
1862	if (res == ERR && _nc_idlok)
1863	    res = scroll_idl(-n, bot + n + 1, top, blank);
1864
1865	/*
1866	 * Clear the newly shifted-in text.
1867	 */
1868	if (res != ERR
1869	    && (non_dest_scroll_region || (memory_above && top == 0))) {
1870	    static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
1871	    for (i = 0; i < -n; i++) {
1872		GoTo(i + top, 0);
1873		ClrToEOL(blank2, FALSE);
1874	    }
1875	}
1876    }
1877
1878    if (res == ERR)
1879	return (ERR);
1880
1881    _nc_scroll_window(curscr, n, top, bot, blank);
1882
1883    /* shift hash values too - they can be reused */
1884    _nc_scroll_oldhash(n, top, bot);
1885
1886    return (OK);
1887}
1888
1889NCURSES_EXPORT(void)
1890_nc_screen_resume(void)
1891{
1892    /* make sure terminal is in a sane known state */
1893    SetAttr(SCREEN_ATTRS(SP), A_NORMAL);
1894    newscr->_clear = TRUE;
1895
1896    /* reset color pairs and definitions */
1897    if (SP->_coloron || SP->_color_defs)
1898	_nc_reset_colors();
1899
1900    /* restore user-defined colors, if any */
1901    if (SP->_color_defs < 0) {
1902	int n;
1903	SP->_color_defs = -(SP->_color_defs);
1904	for (n = 0; n < SP->_color_defs; ++n) {
1905	    if (SP->_color_table[n].init) {
1906		init_color(n,
1907			   SP->_color_table[n].r,
1908			   SP->_color_table[n].g,
1909			   SP->_color_table[n].b);
1910	    }
1911	}
1912    }
1913
1914    if (exit_attribute_mode)
1915	putp(exit_attribute_mode);
1916    else {
1917	/* turn off attributes */
1918	if (exit_alt_charset_mode)
1919	    putp(exit_alt_charset_mode);
1920	if (exit_standout_mode)
1921	    putp(exit_standout_mode);
1922	if (exit_underline_mode)
1923	    putp(exit_underline_mode);
1924    }
1925    if (exit_insert_mode)
1926	putp(exit_insert_mode);
1927    if (enter_am_mode && exit_am_mode)
1928	putp(auto_right_margin ? enter_am_mode : exit_am_mode);
1929}
1930
1931NCURSES_EXPORT(void)
1932_nc_screen_init(void)
1933{
1934    _nc_screen_resume();
1935}
1936
1937/* wrap up screen handling */
1938NCURSES_EXPORT(void)
1939_nc_screen_wrap(void)
1940{
1941    UpdateAttrs(normal);
1942#if NCURSES_EXT_FUNCS
1943    if (SP->_coloron
1944	&& !SP->_default_color) {
1945	static const NCURSES_CH_T blank = NewChar(BLANK_TEXT);
1946	SP->_default_color = TRUE;
1947	_nc_do_color(-1, 0, FALSE, _nc_outch);
1948	SP->_default_color = FALSE;
1949
1950	mvcur(SP->_cursrow, SP->_curscol, screen_lines - 1, 0);
1951
1952	ClrToEOL(blank, TRUE);
1953    }
1954#endif
1955    if (SP->_color_defs) {
1956	_nc_reset_colors();
1957    }
1958}
1959
1960#if USE_XMC_SUPPORT
1961NCURSES_EXPORT(void)
1962_nc_do_xmc_glitch(attr_t previous)
1963{
1964    attr_t chg = XMC_CHANGES(previous ^ AttrOf(SCREEN_ATTRS(SP)));
1965
1966    while (chg != 0) {
1967	if (chg & 1) {
1968	    SP->_curscol += magic_cookie_glitch;
1969	    if (SP->_curscol >= SP->_columns)
1970		wrap_cursor();
1971	    TR(TRACE_UPDATE, ("bumped to %d,%d after cookie", SP->_cursrow, SP->_curscol));
1972	}
1973	chg >>= 1;
1974    }
1975}
1976#endif /* USE_XMC_SUPPORT */
1977