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