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