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