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