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