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