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