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