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