]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tty/tty_update.c
ncurses 6.1 - patch 20180303
[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.297 2017/09/02 21:45:44 Jeb.Rosen 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 != 0 &&
670 #if USE_WIDEC_SUPPORT
671                        (!SP_PARM->_screen_unicode &&
672                         ((AttrOf(ntext0) & A_ALTCHARSET) == 0 ||
673                          (CharOf(ntext0) < ACS_LEN))) &&
674 #endif
675                        runcount > SP_PARM->_rep_cost) {
676                 NCURSES_CH_T temp;
677                 bool wrap_possible = (SP_PARM->_curscol + runcount >=
678                                       screen_columns(SP_PARM));
679                 int rep_count = runcount;
680
681                 if (wrap_possible)
682                     rep_count--;
683
684                 UpdateAttrs(SP_PARM, ntext0);
685                 temp = ntext0;
686                 if ((AttrOf(temp) & A_ALTCHARSET) &&
687                     SP_PARM->_acs_map != 0 &&
688                     (SP_PARM->_acs_map[CharOf(temp)] & A_CHARTEXT) != 0) {
689                     SetChar(temp,
690                             (SP_PARM->_acs_map[CharOf(ntext0)] & A_CHARTEXT),
691                             AttrOf(ntext0) | A_ALTCHARSET);
692                 }
693                 NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
694                                         TPARM_2(repeat_char,
695                                                 CharOf(temp),
696                                                 rep_count),
697                                         1,
698                                         NCURSES_SP_NAME(_nc_outch));
699                 SP_PARM->_curscol += rep_count;
700
701                 if (wrap_possible)
702                     PutChar(NCURSES_SP_ARGx CHREF(ntext0));
703             } else {
704                 for (i = 0; i < runcount; i++)
705                     PutChar(NCURSES_SP_ARGx CHREF(ntext[i]));
706             }
707             ntext += runcount;
708             num -= runcount;
709         }
710         return 0;
711     }
712
713     for (i = 0; i < num; i++)
714         PutChar(NCURSES_SP_ARGx CHREF(ntext[i]));
715     return 0;
716 }
717
718 /*
719  * Output the line in the given range [first .. last]
720  *
721  * If there's a run of identical characters that's long enough to justify
722  * cursor movement, use that also.
723  *
724  * Returns: same as EmitRange
725  */
726 static int
727 PutRange(NCURSES_SP_DCLx
728          const NCURSES_CH_T * otext,
729          const NCURSES_CH_T * ntext,
730          int row,
731          int first, int last)
732 {
733     int rc;
734
735     TR(TRACE_CHARPUT, ("PutRange(%p, %p, %p, %d, %d, %d)",
736                        (void *) SP_PARM,
737                        (const void *) otext,
738                        (const void *) ntext,
739                        row, first, last));
740
741     if (otext != ntext
742         && (last - first + 1) > SP_PARM->_inline_cost) {
743         int i, j, same;
744
745         for (j = first, same = 0; j <= last; j++) {
746             if (!same && isWidecExt(otext[j]))
747                 continue;
748             if (CharEq(otext[j], ntext[j])) {
749                 same++;
750             } else {
751                 if (same > SP_PARM->_inline_cost) {
752                     EmitRange(NCURSES_SP_ARGx ntext + first, j - same - first);
753                     GoTo(NCURSES_SP_ARGx row, first = j);
754                 }
755                 same = 0;
756             }
757         }
758         i = EmitRange(NCURSES_SP_ARGx ntext + first, j - same - first);
759         /*
760          * Always return 1 for the next GoTo() after a PutRange() if we found
761          * identical characters at end of interval
762          */
763         rc = (same == 0 ? i : 1);
764     } else {
765         rc = EmitRange(NCURSES_SP_ARGx ntext + first, last - first + 1);
766     }
767     return rc;
768 }
769
770 /* leave unbracketed here so 'indent' works */
771 #define MARK_NOCHANGE(win,row) \
772                 win->_line[row].firstchar = _NOCHANGE; \
773                 win->_line[row].lastchar = _NOCHANGE; \
774                 if_USE_SCROLL_HINTS(win->_line[row].oldindex = row)
775
776 NCURSES_EXPORT(int)
777 TINFO_DOUPDATE(NCURSES_SP_DCL0)
778 {
779     int i;
780     int nonempty;
781 #if USE_TRACE_TIMES
782     struct tms before, after;
783 #endif /* USE_TRACE_TIMES */
784
785     T((T_CALLED("_nc_tinfo:doupdate(%p)"), (void *) SP_PARM));
786
787     _nc_lock_global(update);
788
789     if (SP_PARM == 0) {
790         _nc_unlock_global(update);
791         returnCode(ERR);
792     }
793 #if !USE_REENTRANT
794     /*
795      * It is "legal" but unlikely that an application could assign a new
796      * value to one of the standard windows.  Check for that possibility
797      * and try to recover.
798      *
799      * We do not allow applications to assign new values in the reentrant
800      * model.
801      */
802 #define SyncScreens(internal,exported) \
803         if (internal == 0) internal = exported; \
804         if (internal != exported) exported = internal
805
806     SyncScreens(CurScreen(SP_PARM), curscr);
807     SyncScreens(NewScreen(SP_PARM), newscr);
808     SyncScreens(StdScreen(SP_PARM), stdscr);
809 #endif
810
811     if (CurScreen(SP_PARM) == 0
812         || NewScreen(SP_PARM) == 0
813         || StdScreen(SP_PARM) == 0) {
814         _nc_unlock_global(update);
815         returnCode(ERR);
816     }
817 #ifdef TRACE
818     if (USE_TRACEF(TRACE_UPDATE)) {
819         if (CurScreen(SP_PARM)->_clear)
820             _tracef("curscr is clear");
821         else
822             _tracedump("curscr", CurScreen(SP_PARM));
823         _tracedump("newscr", NewScreen(SP_PARM));
824         _nc_unlock_global(tracef);
825     }
826 #endif /* TRACE */
827
828     _nc_signal_handler(FALSE);
829
830     if (SP_PARM->_fifohold)
831         SP_PARM->_fifohold--;
832
833 #if USE_SIZECHANGE
834     if ((SP_PARM->_endwin == ewSuspend)
835         || _nc_handle_sigwinch(SP_PARM)) {
836         /*
837          * This is a transparent extension:  XSI does not address it,
838          * and applications need not know that ncurses can do it.
839          *
840          * Check if the terminal size has changed while curses was off
841          * (this can happen in an xterm, for example), and resize the
842          * ncurses data structures accordingly.
843          */
844         _nc_update_screensize(SP_PARM);
845     }
846 #endif
847
848     if (SP_PARM->_endwin == ewSuspend) {
849
850         T(("coming back from shell mode"));
851         NCURSES_SP_NAME(reset_prog_mode) (NCURSES_SP_ARG);
852
853         NCURSES_SP_NAME(_nc_mvcur_resume) (NCURSES_SP_ARG);
854         NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_ARG);
855         SP_PARM->_mouse_resume(SP_PARM);
856
857         SP_PARM->_endwin = ewRunning;
858     }
859 #if USE_TRACE_TIMES
860     /* zero the metering machinery */
861     RESET_OUTCHARS();
862     (void) times(&before);
863 #endif /* USE_TRACE_TIMES */
864
865     /*
866      * This is the support for magic-cookie terminals.  The theory:  we scan
867      * the virtual screen looking for attribute turnons.  Where we find one,
868      * check to make sure it's realizable by seeing if the required number of
869      * un-attributed blanks are present before and after the attributed range;
870      * try to shift the range boundaries over blanks (not changing the screen
871      * display) so this becomes true.  If it is, shift the beginning attribute
872      * change appropriately (the end one, if we've gotten this far, is
873      * guaranteed room for its cookie).  If not, nuke the added attributes out
874      * of the span.
875      */
876 #if USE_XMC_SUPPORT
877     if (magic_cookie_glitch > 0) {
878         int j, k;
879         attr_t rattr = A_NORMAL;
880
881         for (i = 0; i < screen_lines(SP_PARM); i++) {
882             for (j = 0; j < screen_columns(SP_PARM); j++) {
883                 bool failed = FALSE;
884                 NCURSES_CH_T *thisline = NewScreen(SP_PARM)->_line[i].text;
885                 attr_t thisattr = AttrOf(thisline[j]) & SP_PARM->_xmc_triggers;
886                 attr_t turnon = thisattr & ~rattr;
887
888                 /* is an attribute turned on here? */
889                 if (turnon == 0) {
890                     rattr = thisattr;
891                     continue;
892                 }
893
894                 TR(TRACE_ATTRS, ("At (%d, %d): from %s...", i, j, _traceattr(rattr)));
895                 TR(TRACE_ATTRS, ("...to %s", _traceattr(turnon)));
896
897                 /*
898                  * If the attribute change location is a blank with a "safe"
899                  * attribute, undo the attribute turnon.  This may ensure
900                  * there's enough room to set the attribute before the first
901                  * non-blank in the run.
902                  */
903 #define SAFE(scr,a)     (!((a) & (scr)->_xmc_triggers))
904                 if (ISBLANK(thisline[j]) && SAFE(SP_PARM, turnon)) {
905                     RemAttr(thisline[j], turnon);
906                     continue;
907                 }
908
909                 /* check that there's enough room at start of span */
910                 for (k = 1; k <= magic_cookie_glitch; k++) {
911                     if (j - k < 0
912                         || !ISBLANK(thisline[j - k])
913                         || !SAFE(SP_PARM, AttrOf(thisline[j - k]))) {
914                         failed = TRUE;
915                         TR(TRACE_ATTRS, ("No room at start in %d,%d%s%s",
916                                          i, j - k,
917                                          (ISBLANK(thisline[j - k])
918                                           ? ""
919                                           : ":nonblank"),
920                                          (SAFE(SP_PARM, AttrOf(thisline[j - k]))
921                                           ? ""
922                                           : ":unsafe")));
923                         break;
924                     }
925                 }
926                 if (!failed) {
927                     bool end_onscreen = FALSE;
928                     int m, n = j;
929
930                     /* find end of span, if it's onscreen */
931                     for (m = i; m < screen_lines(SP_PARM); m++) {
932                         for (; n < screen_columns(SP_PARM); n++) {
933                             attr_t testattr =
934                             AttrOf(NewScreen(SP_PARM)->_line[m].text[n]);
935                             if ((testattr & SP_PARM->_xmc_triggers) == rattr) {
936                                 end_onscreen = TRUE;
937                                 TR(TRACE_ATTRS,
938                                    ("Range attributed with %s ends at (%d, %d)",
939                                     _traceattr(turnon), m, n));
940                                 goto foundit;
941                             }
942                         }
943                         n = 0;
944                     }
945                     TR(TRACE_ATTRS,
946                        ("Range attributed with %s ends offscreen",
947                         _traceattr(turnon)));
948                   foundit:;
949
950                     if (end_onscreen) {
951                         NCURSES_CH_T *lastline =
952                         NewScreen(SP_PARM)->_line[m].text;
953
954                         /*
955                          * If there are safely-attributed blanks at the end of
956                          * the range, shorten the range.  This will help ensure
957                          * that there is enough room at end of span.
958                          */
959                         while (n >= 0
960                                && ISBLANK(lastline[n])
961                                && SAFE(SP_PARM, AttrOf(lastline[n]))) {
962                             RemAttr(lastline[n--], turnon);
963                         }
964
965                         /* check that there's enough room at end of span */
966                         for (k = 1; k <= magic_cookie_glitch; k++) {
967                             if (n + k >= screen_columns(SP_PARM)
968                                 || !ISBLANK(lastline[n + k])
969                                 || !SAFE(SP_PARM, AttrOf(lastline[n + k]))) {
970                                 failed = TRUE;
971                                 TR(TRACE_ATTRS,
972                                    ("No room at end in %d,%d%s%s",
973                                     i, j - k,
974                                     (ISBLANK(lastline[n + k])
975                                      ? ""
976                                      : ":nonblank"),
977                                     (SAFE(SP_PARM, AttrOf(lastline[n + k]))
978                                      ? ""
979                                      : ":unsafe")));
980                                 break;
981                             }
982                         }
983                     }
984                 }
985
986                 if (failed) {
987                     int p, q = j;
988
989                     TR(TRACE_ATTRS,
990                        ("Clearing %s beginning at (%d, %d)",
991                         _traceattr(turnon), i, j));
992
993                     /* turn off new attributes over span */
994                     for (p = i; p < screen_lines(SP_PARM); p++) {
995                         for (; q < screen_columns(SP_PARM); q++) {
996                             attr_t testattr = AttrOf(newscr->_line[p].text[q]);
997                             if ((testattr & SP_PARM->_xmc_triggers) == rattr)
998                                 goto foundend;
999                             RemAttr(NewScreen(SP_PARM)->_line[p].text[q], turnon);
1000                         }
1001                         q = 0;
1002                     }
1003                   foundend:;
1004                 } else {
1005                     TR(TRACE_ATTRS,
1006                        ("Cookie space for %s found before (%d, %d)",
1007                         _traceattr(turnon), i, j));
1008
1009                     /*
1010                      * Back up the start of range so there's room for cookies
1011                      * before the first nonblank character.
1012                      */
1013                     for (k = 1; k <= magic_cookie_glitch; k++)
1014                         AddAttr(thisline[j - k], turnon);
1015                 }
1016
1017                 rattr = thisattr;
1018             }
1019         }
1020
1021 #ifdef TRACE
1022         /* show altered highlights after magic-cookie check */
1023         if (USE_TRACEF(TRACE_UPDATE)) {
1024             _tracef("After magic-cookie check...");
1025             _tracedump("newscr", NewScreen(SP_PARM));
1026             _nc_unlock_global(tracef);
1027         }
1028 #endif /* TRACE */
1029     }
1030 #endif /* USE_XMC_SUPPORT */
1031
1032     nonempty = 0;
1033     if (CurScreen(SP_PARM)->_clear || NewScreen(SP_PARM)->_clear) {     /* force refresh ? */
1034         ClrUpdate(NCURSES_SP_ARG);
1035         CurScreen(SP_PARM)->_clear = FALSE;     /* reset flag */
1036         NewScreen(SP_PARM)->_clear = FALSE;     /* reset flag */
1037     } else {
1038         int changedlines = CHECK_INTERVAL;
1039
1040         if (check_pending(NCURSES_SP_ARG))
1041             goto cleanup;
1042
1043         nonempty = min(screen_lines(SP_PARM), NewScreen(SP_PARM)->_maxy + 1);
1044
1045         if (SP_PARM->_scrolling) {
1046             NCURSES_SP_NAME(_nc_scroll_optimize) (NCURSES_SP_ARG);
1047         }
1048
1049         nonempty = ClrBottom(NCURSES_SP_ARGx nonempty);
1050
1051         TR(TRACE_UPDATE, ("Transforming lines, nonempty %d", nonempty));
1052         for (i = 0; i < nonempty; i++) {
1053             /*
1054              * Here is our line-breakout optimization.
1055              */
1056             if (changedlines == CHECK_INTERVAL) {
1057                 if (check_pending(NCURSES_SP_ARG))
1058                     goto cleanup;
1059                 changedlines = 0;
1060             }
1061
1062             /*
1063              * newscr->line[i].firstchar is normally set
1064              * by wnoutrefresh.  curscr->line[i].firstchar
1065              * is normally set by _nc_scroll_window in the
1066              * vertical-movement optimization code,
1067              */
1068             if (NewScreen(SP_PARM)->_line[i].firstchar != _NOCHANGE
1069                 || CurScreen(SP_PARM)->_line[i].firstchar != _NOCHANGE) {
1070                 TransformLine(NCURSES_SP_ARGx i);
1071                 changedlines++;
1072             }
1073
1074             /* mark line changed successfully */
1075             if (i <= NewScreen(SP_PARM)->_maxy) {
1076                 MARK_NOCHANGE(NewScreen(SP_PARM), i);
1077             }
1078             if (i <= CurScreen(SP_PARM)->_maxy) {
1079                 MARK_NOCHANGE(CurScreen(SP_PARM), i);
1080             }
1081         }
1082     }
1083
1084     /* put everything back in sync */
1085     for (i = nonempty; i <= NewScreen(SP_PARM)->_maxy; i++) {
1086         MARK_NOCHANGE(NewScreen(SP_PARM), i);
1087     }
1088     for (i = nonempty; i <= CurScreen(SP_PARM)->_maxy; i++) {
1089         MARK_NOCHANGE(CurScreen(SP_PARM), i);
1090     }
1091
1092     if (!NewScreen(SP_PARM)->_leaveok) {
1093         CurScreen(SP_PARM)->_curx = NewScreen(SP_PARM)->_curx;
1094         CurScreen(SP_PARM)->_cury = NewScreen(SP_PARM)->_cury;
1095
1096         GoTo(NCURSES_SP_ARGx CurScreen(SP_PARM)->_cury, CurScreen(SP_PARM)->_curx);
1097     }
1098
1099   cleanup:
1100     /*
1101      * We would like to keep the physical screen in normal mode in case we get
1102      * other processes writing to the screen.  This goal cannot be met for
1103      * magic cookies since it interferes with attributes that may propagate
1104      * past the current position.
1105      */
1106 #if USE_XMC_SUPPORT
1107     if (magic_cookie_glitch != 0)
1108 #endif
1109         UpdateAttrs(SP_PARM, normal);
1110
1111     NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
1112     WINDOW_ATTRS(CurScreen(SP_PARM)) = WINDOW_ATTRS(NewScreen(SP_PARM));
1113
1114 #if USE_TRACE_TIMES
1115     (void) times(&after);
1116     TR(TRACE_TIMES,
1117        ("Update cost: %ld chars, %ld clocks system time, %ld clocks user time",
1118         _nc_outchars,
1119         (long) (after.tms_stime - before.tms_stime),
1120         (long) (after.tms_utime - before.tms_utime)));
1121 #endif /* USE_TRACE_TIMES */
1122
1123     _nc_signal_handler(TRUE);
1124
1125     _nc_unlock_global(update);
1126     returnCode(OK);
1127 }
1128
1129 #if NCURSES_SP_FUNCS && !defined(USE_TERM_DRIVER)
1130 NCURSES_EXPORT(int)
1131 doupdate(void)
1132 {
1133     return TINFO_DOUPDATE(CURRENT_SCREEN);
1134 }
1135 #endif
1136
1137 /*
1138  *      ClrBlank(win)
1139  *
1140  *      Returns the attributed character that corresponds to the "cleared"
1141  *      screen.  If the terminal has the back-color-erase feature, this will be
1142  *      colored according to the wbkgd() call.
1143  *
1144  *      We treat 'curscr' specially because it isn't supposed to be set directly
1145  *      in the wbkgd() call.  Assume 'stdscr' for this case.
1146  */
1147 #define BCE_ATTRS (A_NORMAL|A_COLOR)
1148 #define BCE_BKGD(sp,win) (((win) == CurScreen(sp) ? StdScreen(sp) : (win))->_nc_bkgd)
1149
1150 static NCURSES_INLINE NCURSES_CH_T
1151 ClrBlank(NCURSES_SP_DCLx WINDOW *win)
1152 {
1153     NCURSES_CH_T blank = blankchar;
1154     if (back_color_erase)
1155         AddAttr(blank, (AttrOf(BCE_BKGD(SP_PARM, win)) & BCE_ATTRS));
1156     return blank;
1157 }
1158
1159 /*
1160 **      ClrUpdate()
1161 **
1162 **      Update by clearing and redrawing the entire screen.
1163 **
1164 */
1165
1166 static void
1167 ClrUpdate(NCURSES_SP_DCL0)
1168 {
1169     TR(TRACE_UPDATE, (T_CALLED("ClrUpdate")));
1170     if (0 != SP_PARM) {
1171         int i;
1172         NCURSES_CH_T blank = ClrBlank(NCURSES_SP_ARGx StdScreen(SP_PARM));
1173         int nonempty = min(screen_lines(SP_PARM),
1174                            NewScreen(SP_PARM)->_maxy + 1);
1175
1176         ClearScreen(NCURSES_SP_ARGx blank);
1177
1178         TR(TRACE_UPDATE, ("updating screen from scratch"));
1179
1180         nonempty = ClrBottom(NCURSES_SP_ARGx nonempty);
1181
1182         for (i = 0; i < nonempty; i++)
1183             TransformLine(NCURSES_SP_ARGx i);
1184     }
1185     TR(TRACE_UPDATE, (T_RETURN("")));
1186 }
1187
1188 /*
1189 **      ClrToEOL(blank)
1190 **
1191 **      Clear to end of current line, starting at the cursor position
1192 */
1193
1194 static void
1195 ClrToEOL(NCURSES_SP_DCLx NCURSES_CH_T blank, int needclear)
1196 {
1197     if (CurScreen(SP_PARM) != 0
1198         && SP_PARM->_cursrow >= 0) {
1199         int j;
1200
1201         for (j = SP_PARM->_curscol; j < screen_columns(SP_PARM); j++) {
1202             if (j >= 0) {
1203                 NCURSES_CH_T *cp =
1204                 &(CurScreen(SP_PARM)->_line[SP_PARM->_cursrow].text[j]);
1205
1206                 if (!CharEq(*cp, blank)) {
1207                     *cp = blank;
1208                     needclear = TRUE;
1209                 }
1210             }
1211         }
1212     }
1213
1214     if (needclear) {
1215         UpdateAttrs(SP_PARM, blank);
1216         if (clr_eol && SP_PARM->_el_cost <= (screen_columns(SP_PARM) - SP_PARM->_curscol)) {
1217             NCURSES_PUTP2("clr_eol", clr_eol);
1218         } else {
1219             int count = (screen_columns(SP_PARM) - SP_PARM->_curscol);
1220             while (count-- > 0)
1221                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1222         }
1223     }
1224 }
1225
1226 /*
1227 **      ClrToEOS(blank)
1228 **
1229 **      Clear to end of screen, starting at the cursor position
1230 */
1231
1232 static void
1233 ClrToEOS(NCURSES_SP_DCLx NCURSES_CH_T blank)
1234 {
1235     int row, col;
1236
1237     row = SP_PARM->_cursrow;
1238     col = SP_PARM->_curscol;
1239
1240     if (row < 0)
1241         row = 0;
1242     if (col < 0)
1243         col = 0;
1244
1245     UpdateAttrs(SP_PARM, blank);
1246     TPUTS_TRACE("clr_eos");
1247     NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1248                             clr_eos,
1249                             screen_lines(SP_PARM) - row,
1250                             NCURSES_SP_NAME(_nc_outch));
1251
1252     while (col < screen_columns(SP_PARM))
1253         CurScreen(SP_PARM)->_line[row].text[col++] = blank;
1254
1255     for (row++; row < screen_lines(SP_PARM); row++) {
1256         for (col = 0; col < screen_columns(SP_PARM); col++)
1257             CurScreen(SP_PARM)->_line[row].text[col] = blank;
1258     }
1259 }
1260
1261 /*
1262  *      ClrBottom(total)
1263  *
1264  *      Test if clearing the end of the screen would satisfy part of the
1265  *      screen-update.  Do this by scanning backwards through the lines in the
1266  *      screen, checking if each is blank, and one or more are changed.
1267  */
1268 static int
1269 ClrBottom(NCURSES_SP_DCLx int total)
1270 {
1271     int top = total;
1272     int last = min(screen_columns(SP_PARM), NewScreen(SP_PARM)->_maxx + 1);
1273     NCURSES_CH_T blank = NewScreen(SP_PARM)->_line[total - 1].text[last - 1];
1274
1275     if (clr_eos && can_clear_with(NCURSES_SP_ARGx CHREF(blank))) {
1276         int row;
1277
1278         for (row = total - 1; row >= 0; row--) {
1279             int col;
1280             bool ok;
1281
1282             for (col = 0, ok = TRUE; ok && col < last; col++) {
1283                 ok = (CharEq(NewScreen(SP_PARM)->_line[row].text[col], blank));
1284             }
1285             if (!ok)
1286                 break;
1287
1288             for (col = 0; ok && col < last; col++) {
1289                 ok = (CharEq(CurScreen(SP_PARM)->_line[row].text[col], blank));
1290             }
1291             if (!ok)
1292                 top = row;
1293         }
1294
1295         /* don't use clr_eos for just one line if clr_eol available */
1296         if (top < total) {
1297             GoTo(NCURSES_SP_ARGx top, 0);
1298             ClrToEOS(NCURSES_SP_ARGx blank);
1299             if (SP_PARM->oldhash && SP_PARM->newhash) {
1300                 for (row = top; row < screen_lines(SP_PARM); row++)
1301                     SP_PARM->oldhash[row] = SP_PARM->newhash[row];
1302             }
1303         }
1304     }
1305     return top;
1306 }
1307
1308 #if USE_XMC_SUPPORT
1309 #if USE_WIDEC_SUPPORT
1310 #define check_xmc_transition(sp, a, b)                                  \
1311     ((((a)->attr ^ (b)->attr) & ~((a)->attr) & (sp)->_xmc_triggers) != 0)
1312 #define xmc_turn_on(sp,a,b) check_xmc_transition(sp,&(a), &(b))
1313 #else
1314 #define xmc_turn_on(sp,a,b) ((((a)^(b)) & ~(a) & (sp)->_xmc_triggers) != 0)
1315 #endif
1316
1317 #define xmc_new(sp,r,c) NewScreen(sp)->_line[r].text[c]
1318 #define xmc_turn_off(sp,a,b) xmc_turn_on(sp,b,a)
1319 #endif /* USE_XMC_SUPPORT */
1320
1321 /*
1322 **      TransformLine(lineno)
1323 **
1324 **      Transform the given line in curscr to the one in newscr, using
1325 **      Insert/Delete Character if idcok && has_ic().
1326 **
1327 **              firstChar = position of first different character in line
1328 **              oLastChar = position of last different character in old line
1329 **              nLastChar = position of last different character in new line
1330 **
1331 **              move to firstChar
1332 **              overwrite chars up to min(oLastChar, nLastChar)
1333 **              if oLastChar < nLastChar
1334 **                      insert newLine[oLastChar+1..nLastChar]
1335 **              else
1336 **                      delete oLastChar - nLastChar spaces
1337 */
1338
1339 static void
1340 TransformLine(NCURSES_SP_DCLx int const lineno)
1341 {
1342     int firstChar, oLastChar, nLastChar;
1343     NCURSES_CH_T *newLine = NewScreen(SP_PARM)->_line[lineno].text;
1344     NCURSES_CH_T *oldLine = CurScreen(SP_PARM)->_line[lineno].text;
1345     int n;
1346     bool attrchanged = FALSE;
1347
1348     TR(TRACE_UPDATE, (T_CALLED("TransformLine(%p, %d)"), (void *) SP_PARM, lineno));
1349
1350     /* copy new hash value to old one */
1351     if (SP_PARM->oldhash && SP_PARM->newhash)
1352         SP_PARM->oldhash[lineno] = SP_PARM->newhash[lineno];
1353
1354     /*
1355      * If we have colors, there is the possibility of having two color pairs
1356      * that display as the same colors.  For instance, Lynx does this.  Check
1357      * for this case, and update the old line with the new line's colors when
1358      * they are equivalent.
1359      */
1360     if (SP_PARM->_coloron) {
1361         int oldPair;
1362         int newPair;
1363
1364         for (n = 0; n < screen_columns(SP_PARM); n++) {
1365             if (!CharEq(newLine[n], oldLine[n])) {
1366                 oldPair = GetPair(oldLine[n]);
1367                 newPair = GetPair(newLine[n]);
1368                 if (oldPair != newPair
1369                     && unColor(oldLine[n]) == unColor(newLine[n])) {
1370                     if (oldPair < SP_PARM->_pair_limit
1371                         && newPair < SP_PARM->_pair_limit
1372                         && (isSamePair(SP_PARM->_color_pairs[oldPair],
1373                                        SP_PARM->_color_pairs[newPair]))) {
1374                         SetPair(oldLine[n], GetPair(newLine[n]));
1375                     }
1376                 }
1377             }
1378         }
1379     }
1380
1381     if (ceol_standout_glitch && clr_eol) {
1382         firstChar = 0;
1383         while (firstChar < screen_columns(SP_PARM)) {
1384             if (!SameAttrOf(newLine[firstChar], oldLine[firstChar])) {
1385                 attrchanged = TRUE;
1386                 break;
1387             }
1388             firstChar++;
1389         }
1390     }
1391
1392     firstChar = 0;
1393
1394     if (attrchanged) {          /* we may have to disregard the whole line */
1395         GoTo(NCURSES_SP_ARGx lineno, firstChar);
1396         ClrToEOL(NCURSES_SP_ARGx
1397                  ClrBlank(NCURSES_SP_ARGx
1398                           CurScreen(SP_PARM)), FALSE);
1399         PutRange(NCURSES_SP_ARGx
1400                  oldLine, newLine, lineno, 0,
1401                  screen_columns(SP_PARM) - 1);
1402 #if USE_XMC_SUPPORT
1403
1404         /*
1405          * This is a very simple loop to paint characters which may have the
1406          * magic cookie glitch embedded.  It doesn't know much about video
1407          * attributes which are continued from one line to the next.  It
1408          * assumes that we have filtered out requests for attribute changes
1409          * that do not get mapped to blank positions.
1410          *
1411          * FIXME: we are not keeping track of where we put the cookies, so this
1412          * will work properly only once, since we may overwrite a cookie in a
1413          * following operation.
1414          */
1415     } else if (magic_cookie_glitch > 0) {
1416         GoTo(NCURSES_SP_ARGx lineno, firstChar);
1417         for (n = 0; n < screen_columns(SP_PARM); n++) {
1418             int m = n + magic_cookie_glitch;
1419
1420             /* check for turn-on:
1421              * If we are writing an attributed blank, where the
1422              * previous cell is not attributed.
1423              */
1424             if (ISBLANK(newLine[n])
1425                 && ((n > 0
1426                      && xmc_turn_on(SP_PARM, newLine[n - 1], newLine[n]))
1427                     || (n == 0
1428                         && lineno > 0
1429                         && xmc_turn_on(SP_PARM,
1430                                        xmc_new(SP_PARM, lineno - 1,
1431                                                screen_columns(SP_PARM) - 1),
1432                                        newLine[n])))) {
1433                 n = m;
1434             }
1435
1436             PutChar(NCURSES_SP_ARGx CHREF(newLine[n]));
1437
1438             /* check for turn-off:
1439              * If we are writing an attributed non-blank, where the
1440              * next cell is blank, and not attributed.
1441              */
1442             if (!ISBLANK(newLine[n])
1443                 && ((n + 1 < screen_columns(SP_PARM)
1444                      && xmc_turn_off(SP_PARM, newLine[n], newLine[n + 1]))
1445                     || (n + 1 >= screen_columns(SP_PARM)
1446                         && lineno + 1 < screen_lines(SP_PARM)
1447                         && xmc_turn_off(SP_PARM,
1448                                         newLine[n],
1449                                         xmc_new(SP_PARM, lineno + 1, 0))))) {
1450                 n = m;
1451             }
1452
1453         }
1454 #endif
1455     } else {
1456         NCURSES_CH_T blank;
1457
1458         /* it may be cheap to clear leading whitespace with clr_bol */
1459         blank = newLine[0];
1460         if (clr_bol && can_clear_with(NCURSES_SP_ARGx CHREF(blank))) {
1461             int oFirstChar, nFirstChar;
1462
1463             for (oFirstChar = 0;
1464                  oFirstChar < screen_columns(SP_PARM);
1465                  oFirstChar++)
1466                 if (!CharEq(oldLine[oFirstChar], blank))
1467                     break;
1468             for (nFirstChar = 0;
1469                  nFirstChar < screen_columns(SP_PARM);
1470                  nFirstChar++)
1471                 if (!CharEq(newLine[nFirstChar], blank))
1472                     break;
1473
1474             if (nFirstChar == oFirstChar) {
1475                 firstChar = nFirstChar;
1476                 /* find the first differing character */
1477                 while (firstChar < screen_columns(SP_PARM)
1478                        && CharEq(newLine[firstChar], oldLine[firstChar]))
1479                     firstChar++;
1480             } else if (oFirstChar > nFirstChar) {
1481                 firstChar = nFirstChar;
1482             } else {            /* oFirstChar < nFirstChar */
1483                 firstChar = oFirstChar;
1484                 if (SP_PARM->_el1_cost < nFirstChar - oFirstChar) {
1485                     if (nFirstChar >= screen_columns(SP_PARM)
1486                         && SP_PARM->_el_cost <= SP_PARM->_el1_cost) {
1487                         GoTo(NCURSES_SP_ARGx lineno, 0);
1488                         UpdateAttrs(SP_PARM, blank);
1489                         NCURSES_PUTP2("clr_eol", clr_eol);
1490                     } else {
1491                         GoTo(NCURSES_SP_ARGx lineno, nFirstChar - 1);
1492                         UpdateAttrs(SP_PARM, blank);
1493                         NCURSES_PUTP2("clr_bol", clr_bol);
1494                     }
1495
1496                     while (firstChar < nFirstChar)
1497                         oldLine[firstChar++] = blank;
1498                 }
1499             }
1500         } else {
1501             /* find the first differing character */
1502             while (firstChar < screen_columns(SP_PARM)
1503                    && CharEq(newLine[firstChar], oldLine[firstChar]))
1504                 firstChar++;
1505         }
1506         /* if there wasn't one, we're done */
1507         if (firstChar >= screen_columns(SP_PARM)) {
1508             TR(TRACE_UPDATE, (T_RETURN("")));
1509             return;
1510         }
1511
1512         blank = newLine[screen_columns(SP_PARM) - 1];
1513
1514         if (!can_clear_with(NCURSES_SP_ARGx CHREF(blank))) {
1515             /* find the last differing character */
1516             nLastChar = screen_columns(SP_PARM) - 1;
1517
1518             while (nLastChar > firstChar
1519                    && CharEq(newLine[nLastChar], oldLine[nLastChar]))
1520                 nLastChar--;
1521
1522             if (nLastChar >= firstChar) {
1523                 GoTo(NCURSES_SP_ARGx lineno, firstChar);
1524                 PutRange(NCURSES_SP_ARGx
1525                          oldLine,
1526                          newLine,
1527                          lineno,
1528                          firstChar,
1529                          nLastChar);
1530                 memcpy(oldLine + firstChar,
1531                        newLine + firstChar,
1532                        (unsigned) (nLastChar - firstChar + 1) * sizeof(NCURSES_CH_T));
1533             }
1534             TR(TRACE_UPDATE, (T_RETURN("")));
1535             return;
1536         }
1537
1538         /* find last non-blank character on old line */
1539         oLastChar = screen_columns(SP_PARM) - 1;
1540         while (oLastChar > firstChar && CharEq(oldLine[oLastChar], blank))
1541             oLastChar--;
1542
1543         /* find last non-blank character on new line */
1544         nLastChar = screen_columns(SP_PARM) - 1;
1545         while (nLastChar > firstChar && CharEq(newLine[nLastChar], blank))
1546             nLastChar--;
1547
1548         if ((nLastChar == firstChar)
1549             && (SP_PARM->_el_cost < (oLastChar - nLastChar))) {
1550             GoTo(NCURSES_SP_ARGx lineno, firstChar);
1551             if (!CharEq(newLine[firstChar], blank))
1552                 PutChar(NCURSES_SP_ARGx CHREF(newLine[firstChar]));
1553             ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1554         } else if ((nLastChar != oLastChar)
1555                    && (!CharEq(newLine[nLastChar], oldLine[oLastChar])
1556                        || !(SP_PARM->_nc_sp_idcok
1557                             && NCURSES_SP_NAME(has_ic) (NCURSES_SP_ARG)))) {
1558             GoTo(NCURSES_SP_ARGx lineno, firstChar);
1559             if ((oLastChar - nLastChar) > SP_PARM->_el_cost) {
1560                 if (PutRange(NCURSES_SP_ARGx
1561                              oldLine,
1562                              newLine,
1563                              lineno,
1564                              firstChar,
1565                              nLastChar)) {
1566                     GoTo(NCURSES_SP_ARGx lineno, nLastChar + 1);
1567                 }
1568                 ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1569             } else {
1570                 n = max(nLastChar, oLastChar);
1571                 PutRange(NCURSES_SP_ARGx
1572                          oldLine,
1573                          newLine,
1574                          lineno,
1575                          firstChar,
1576                          n);
1577             }
1578         } else {
1579             int nLastNonblank = nLastChar;
1580             int oLastNonblank = oLastChar;
1581
1582             /* find the last characters that really differ */
1583             /* can be -1 if no characters differ */
1584             while (CharEq(newLine[nLastChar], oldLine[oLastChar])) {
1585                 /* don't split a wide char */
1586                 if (isWidecExt(newLine[nLastChar]) &&
1587                     !CharEq(newLine[nLastChar - 1], oldLine[oLastChar - 1]))
1588                     break;
1589                 nLastChar--;
1590                 oLastChar--;
1591                 if (nLastChar == -1 || oLastChar == -1)
1592                     break;
1593             }
1594
1595             n = min(oLastChar, nLastChar);
1596             if (n >= firstChar) {
1597                 GoTo(NCURSES_SP_ARGx lineno, firstChar);
1598                 PutRange(NCURSES_SP_ARGx
1599                          oldLine,
1600                          newLine,
1601                          lineno,
1602                          firstChar,
1603                          n);
1604             }
1605
1606             if (oLastChar < nLastChar) {
1607                 int m = max(nLastNonblank, oLastNonblank);
1608 #if USE_WIDEC_SUPPORT
1609                 if (n) {
1610                     while (isWidecExt(newLine[n + 1]) && n) {
1611                         --n;
1612                         --oLastChar;    /* increase cost */
1613                     }
1614                 } else if (n >= firstChar &&
1615                            isWidecBase(newLine[n])) {
1616                     while (isWidecExt(newLine[n + 1])) {
1617                         ++n;
1618                         ++oLastChar;    /* decrease cost */
1619                     }
1620                 }
1621 #endif
1622                 GoTo(NCURSES_SP_ARGx lineno, n + 1);
1623                 if ((nLastChar < nLastNonblank)
1624                     || InsCharCost(SP_PARM, nLastChar - oLastChar) > (m - n)) {
1625                     PutRange(NCURSES_SP_ARGx
1626                              oldLine,
1627                              newLine,
1628                              lineno,
1629                              n + 1,
1630                              m);
1631                 } else {
1632                     InsStr(NCURSES_SP_ARGx &newLine[n + 1], nLastChar - oLastChar);
1633                 }
1634             } else if (oLastChar > nLastChar) {
1635                 GoTo(NCURSES_SP_ARGx lineno, n + 1);
1636                 if (DelCharCost(SP_PARM, oLastChar - nLastChar)
1637                     > SP_PARM->_el_cost + nLastNonblank - (n + 1)) {
1638                     if (PutRange(NCURSES_SP_ARGx oldLine, newLine, lineno,
1639                                  n + 1, nLastNonblank)) {
1640                         GoTo(NCURSES_SP_ARGx lineno, nLastNonblank + 1);
1641                     }
1642                     ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1643                 } else {
1644                     /*
1645                      * The delete-char sequence will
1646                      * effectively shift in blanks from the
1647                      * right margin of the screen.  Ensure
1648                      * that they are the right color by
1649                      * setting the video attributes from
1650                      * the last character on the row.
1651                      */
1652                     UpdateAttrs(SP_PARM, blank);
1653                     DelChar(NCURSES_SP_ARGx oLastChar - nLastChar);
1654                 }
1655             }
1656         }
1657     }
1658
1659     /* update the code's internal representation */
1660     if (screen_columns(SP_PARM) > firstChar)
1661         memcpy(oldLine + firstChar,
1662                newLine + firstChar,
1663                (unsigned) (screen_columns(SP_PARM) - firstChar) * sizeof(NCURSES_CH_T));
1664     TR(TRACE_UPDATE, (T_RETURN("")));
1665     return;
1666 }
1667
1668 /*
1669 **      ClearScreen(blank)
1670 **
1671 **      Clear the physical screen and put cursor at home
1672 **
1673 */
1674
1675 static void
1676 ClearScreen(NCURSES_SP_DCLx NCURSES_CH_T blank)
1677 {
1678     int i, j;
1679     bool fast_clear = (clear_screen || clr_eos || clr_eol);
1680
1681     TR(TRACE_UPDATE, ("ClearScreen() called"));
1682
1683 #if NCURSES_EXT_FUNCS
1684     if (SP_PARM->_coloron
1685         && !SP_PARM->_default_color) {
1686         NCURSES_SP_NAME(_nc_do_color) (NCURSES_SP_ARGx
1687                                        (short) GET_SCREEN_PAIR(SP_PARM),
1688                                        0,
1689                                        FALSE,
1690                                        NCURSES_SP_NAME(_nc_outch));
1691         if (!back_color_erase) {
1692             fast_clear = FALSE;
1693         }
1694     }
1695 #endif
1696
1697     if (fast_clear) {
1698         if (clear_screen) {
1699             UpdateAttrs(SP_PARM, blank);
1700             NCURSES_PUTP2("clear_screen", clear_screen);
1701             SP_PARM->_cursrow = SP_PARM->_curscol = 0;
1702             position_check(NCURSES_SP_ARGx
1703                            SP_PARM->_cursrow,
1704                            SP_PARM->_curscol,
1705                            "ClearScreen");
1706         } else if (clr_eos) {
1707             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1708             GoTo(NCURSES_SP_ARGx 0, 0);
1709             UpdateAttrs(SP_PARM, blank);
1710             TPUTS_TRACE("clr_eos");
1711             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1712                                     clr_eos,
1713                                     screen_lines(SP_PARM),
1714                                     NCURSES_SP_NAME(_nc_outch));
1715         } else if (clr_eol) {
1716             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1717             UpdateAttrs(SP_PARM, blank);
1718             for (i = 0; i < screen_lines(SP_PARM); i++) {
1719                 GoTo(NCURSES_SP_ARGx i, 0);
1720                 NCURSES_PUTP2("clr_eol", clr_eol);
1721             }
1722             GoTo(NCURSES_SP_ARGx 0, 0);
1723         }
1724     } else {
1725         UpdateAttrs(SP_PARM, blank);
1726         for (i = 0; i < screen_lines(SP_PARM); i++) {
1727             GoTo(NCURSES_SP_ARGx i, 0);
1728             for (j = 0; j < screen_columns(SP_PARM); j++)
1729                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1730         }
1731         GoTo(NCURSES_SP_ARGx 0, 0);
1732     }
1733
1734     for (i = 0; i < screen_lines(SP_PARM); i++) {
1735         for (j = 0; j < screen_columns(SP_PARM); j++)
1736             CurScreen(SP_PARM)->_line[i].text[j] = blank;
1737     }
1738
1739     TR(TRACE_UPDATE, ("screen cleared"));
1740 }
1741
1742 /*
1743 **      InsStr(line, count)
1744 **
1745 **      Insert the count characters pointed to by line.
1746 **
1747 */
1748
1749 static void
1750 InsStr(NCURSES_SP_DCLx NCURSES_CH_T * line, int count)
1751 {
1752     TR(TRACE_UPDATE, ("InsStr(%p, %p,%d) called",
1753                       (void *) SP_PARM,
1754                       (void *) line, count));
1755
1756     /* Prefer parm_ich as it has the smallest cost - no need to shift
1757      * the whole line on each character. */
1758     /* The order must match that of InsCharCost. */
1759     if (parm_ich) {
1760         TPUTS_TRACE("parm_ich");
1761         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1762                                 TPARM_1(parm_ich, count),
1763                                 1,
1764                                 NCURSES_SP_NAME(_nc_outch));
1765         while (count > 0) {
1766             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1767             line++;
1768             count--;
1769         }
1770     } else if (enter_insert_mode && exit_insert_mode) {
1771         NCURSES_PUTP2("enter_insert_mode", enter_insert_mode);
1772         while (count > 0) {
1773             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1774             if (insert_padding) {
1775                 NCURSES_PUTP2("insert_padding", insert_padding);
1776             }
1777             line++;
1778             count--;
1779         }
1780         NCURSES_PUTP2("exit_insert_mode", exit_insert_mode);
1781     } else {
1782         while (count > 0) {
1783             NCURSES_PUTP2("insert_character", insert_character);
1784             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1785             if (insert_padding) {
1786                 NCURSES_PUTP2("insert_padding", insert_padding);
1787             }
1788             line++;
1789             count--;
1790         }
1791     }
1792     position_check(NCURSES_SP_ARGx
1793                    SP_PARM->_cursrow,
1794                    SP_PARM->_curscol, "InsStr");
1795 }
1796
1797 /*
1798 **      DelChar(count)
1799 **
1800 **      Delete count characters at current position
1801 **
1802 */
1803
1804 static void
1805 DelChar(NCURSES_SP_DCLx int count)
1806 {
1807     TR(TRACE_UPDATE, ("DelChar(%p, %d) called, position = (%ld,%ld)",
1808                       (void *) SP_PARM, count,
1809                       (long) NewScreen(SP_PARM)->_cury,
1810                       (long) NewScreen(SP_PARM)->_curx));
1811
1812     if (parm_dch) {
1813         TPUTS_TRACE("parm_dch");
1814         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1815                                 TPARM_1(parm_dch, count),
1816                                 1,
1817                                 NCURSES_SP_NAME(_nc_outch));
1818     } else {
1819         int n;
1820
1821         for (n = 0; n < count; n++) {
1822             NCURSES_PUTP2("delete_character", delete_character);
1823         }
1824     }
1825 }
1826
1827 /*
1828  * Physical-scrolling support
1829  *
1830  * This code was adapted from Keith Bostic's hardware scrolling
1831  * support for 4.4BSD curses.  I (esr) translated it to use terminfo
1832  * capabilities, narrowed the call interface slightly, and cleaned
1833  * up some convoluted tests.  I also added support for the memory_above
1834  * memory_below, and non_dest_scroll_region capabilities.
1835  *
1836  * For this code to work, we must have either
1837  * change_scroll_region and scroll forward/reverse commands, or
1838  * insert and delete line capabilities.
1839  * When the scrolling region has been set, the cursor has to
1840  * be at the last line of the region to make the scroll up
1841  * happen, or on the first line of region to scroll down.
1842  *
1843  * This code makes one aesthetic decision in the opposite way from
1844  * BSD curses.  BSD curses preferred pairs of il/dl operations
1845  * over scrolls, allegedly because il/dl looked faster.  We, on
1846  * the other hand, prefer scrolls because (a) they're just as fast
1847  * on many terminals and (b) using them avoids bouncing an
1848  * unchanged bottom section of the screen up and down, which is
1849  * visually nasty.
1850  *
1851  * (lav): added more cases, used dl/il when bot==maxy and in csr case.
1852  *
1853  * I used assumption that capabilities il/il1/dl/dl1 work inside
1854  * changed scroll region not shifting screen contents outside of it.
1855  * If there are any terminals behaving different way, it would be
1856  * necessary to add some conditions to scroll_csr_forward/backward.
1857  */
1858
1859 /* Try to scroll up assuming given csr (miny, maxy). Returns ERR on failure */
1860 static int
1861 scroll_csr_forward(NCURSES_SP_DCLx
1862                    int n,
1863                    int top,
1864                    int bot,
1865                    int miny,
1866                    int maxy,
1867                    NCURSES_CH_T blank)
1868 {
1869     int i;
1870
1871     if (n == 1 && scroll_forward && top == miny && bot == maxy) {
1872         GoTo(NCURSES_SP_ARGx bot, 0);
1873         UpdateAttrs(SP_PARM, blank);
1874         NCURSES_PUTP2("scroll_forward", scroll_forward);
1875     } else if (n == 1 && delete_line && bot == maxy) {
1876         GoTo(NCURSES_SP_ARGx top, 0);
1877         UpdateAttrs(SP_PARM, blank);
1878         NCURSES_PUTP2("delete_line", delete_line);
1879     } else if (parm_index && top == miny && bot == maxy) {
1880         GoTo(NCURSES_SP_ARGx bot, 0);
1881         UpdateAttrs(SP_PARM, blank);
1882         TPUTS_TRACE("parm_index");
1883         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1884                                 TPARM_2(parm_index, n, 0),
1885                                 n,
1886                                 NCURSES_SP_NAME(_nc_outch));
1887     } else if (parm_delete_line && bot == maxy) {
1888         GoTo(NCURSES_SP_ARGx top, 0);
1889         UpdateAttrs(SP_PARM, blank);
1890         TPUTS_TRACE("parm_delete_line");
1891         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1892                                 TPARM_2(parm_delete_line, n, 0),
1893                                 n,
1894                                 NCURSES_SP_NAME(_nc_outch));
1895     } else if (scroll_forward && top == miny && bot == maxy) {
1896         GoTo(NCURSES_SP_ARGx bot, 0);
1897         UpdateAttrs(SP_PARM, blank);
1898         for (i = 0; i < n; i++) {
1899             NCURSES_PUTP2("scroll_forward", scroll_forward);
1900         }
1901     } else if (delete_line && bot == maxy) {
1902         GoTo(NCURSES_SP_ARGx top, 0);
1903         UpdateAttrs(SP_PARM, blank);
1904         for (i = 0; i < n; i++) {
1905             NCURSES_PUTP2("delete_line", delete_line);
1906         }
1907     } else
1908         return ERR;
1909
1910 #if NCURSES_EXT_FUNCS
1911     if (FILL_BCE(SP_PARM)) {
1912         int j;
1913         for (i = 0; i < n; i++) {
1914             GoTo(NCURSES_SP_ARGx bot - i, 0);
1915             for (j = 0; j < screen_columns(SP_PARM); j++)
1916                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1917         }
1918     }
1919 #endif
1920     return OK;
1921 }
1922
1923 /* Try to scroll down assuming given csr (miny, maxy). Returns ERR on failure */
1924 /* n > 0 */
1925 static int
1926 scroll_csr_backward(NCURSES_SP_DCLx
1927                     int n,
1928                     int top,
1929                     int bot,
1930                     int miny,
1931                     int maxy,
1932                     NCURSES_CH_T blank)
1933 {
1934     int i;
1935
1936     if (n == 1 && scroll_reverse && top == miny && bot == maxy) {
1937         GoTo(NCURSES_SP_ARGx top, 0);
1938         UpdateAttrs(SP_PARM, blank);
1939         NCURSES_PUTP2("scroll_reverse", scroll_reverse);
1940     } else if (n == 1 && insert_line && bot == maxy) {
1941         GoTo(NCURSES_SP_ARGx top, 0);
1942         UpdateAttrs(SP_PARM, blank);
1943         NCURSES_PUTP2("insert_line", insert_line);
1944     } else if (parm_rindex && top == miny && bot == maxy) {
1945         GoTo(NCURSES_SP_ARGx top, 0);
1946         UpdateAttrs(SP_PARM, blank);
1947         TPUTS_TRACE("parm_rindex");
1948         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1949                                 TPARM_2(parm_rindex, n, 0),
1950                                 n,
1951                                 NCURSES_SP_NAME(_nc_outch));
1952     } else if (parm_insert_line && bot == maxy) {
1953         GoTo(NCURSES_SP_ARGx top, 0);
1954         UpdateAttrs(SP_PARM, blank);
1955         TPUTS_TRACE("parm_insert_line");
1956         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1957                                 TPARM_2(parm_insert_line, n, 0),
1958                                 n,
1959                                 NCURSES_SP_NAME(_nc_outch));
1960     } else if (scroll_reverse && top == miny && bot == maxy) {
1961         GoTo(NCURSES_SP_ARGx top, 0);
1962         UpdateAttrs(SP_PARM, blank);
1963         for (i = 0; i < n; i++) {
1964             NCURSES_PUTP2("scroll_reverse", scroll_reverse);
1965         }
1966     } else if (insert_line && bot == maxy) {
1967         GoTo(NCURSES_SP_ARGx top, 0);
1968         UpdateAttrs(SP_PARM, blank);
1969         for (i = 0; i < n; i++) {
1970             NCURSES_PUTP2("insert_line", insert_line);
1971         }
1972     } else
1973         return ERR;
1974
1975 #if NCURSES_EXT_FUNCS
1976     if (FILL_BCE(SP_PARM)) {
1977         int j;
1978         for (i = 0; i < n; i++) {
1979             GoTo(NCURSES_SP_ARGx top + i, 0);
1980             for (j = 0; j < screen_columns(SP_PARM); j++)
1981                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1982         }
1983     }
1984 #endif
1985     return OK;
1986 }
1987
1988 /* scroll by using delete_line at del and insert_line at ins */
1989 /* n > 0 */
1990 static int
1991 scroll_idl(NCURSES_SP_DCLx int n, int del, int ins, NCURSES_CH_T blank)
1992 {
1993     int i;
1994
1995     if (!((parm_delete_line || delete_line) && (parm_insert_line || insert_line)))
1996         return ERR;
1997
1998     GoTo(NCURSES_SP_ARGx del, 0);
1999     UpdateAttrs(SP_PARM, blank);
2000     if (n == 1 && delete_line) {
2001         NCURSES_PUTP2("delete_line", delete_line);
2002     } else if (parm_delete_line) {
2003         TPUTS_TRACE("parm_delete_line");
2004         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
2005                                 TPARM_2(parm_delete_line, n, 0),
2006                                 n,
2007                                 NCURSES_SP_NAME(_nc_outch));
2008     } else {                    /* if (delete_line) */
2009         for (i = 0; i < n; i++) {
2010             NCURSES_PUTP2("delete_line", delete_line);
2011         }
2012     }
2013
2014     GoTo(NCURSES_SP_ARGx ins, 0);
2015     UpdateAttrs(SP_PARM, blank);
2016     if (n == 1 && insert_line) {
2017         NCURSES_PUTP2("insert_line", insert_line);
2018     } else if (parm_insert_line) {
2019         TPUTS_TRACE("parm_insert_line");
2020         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
2021                                 TPARM_2(parm_insert_line, n, 0),
2022                                 n,
2023                                 NCURSES_SP_NAME(_nc_outch));
2024     } else {                    /* if (insert_line) */
2025         for (i = 0; i < n; i++) {
2026             NCURSES_PUTP2("insert_line", insert_line);
2027         }
2028     }
2029
2030     return OK;
2031 }
2032
2033 /*
2034  * Note:  some terminals require the cursor to be within the scrolling margins
2035  * before setting them.  Generally, the cursor must be at the appropriate end
2036  * of the scrolling margins when issuing an indexing operation (it is not
2037  * apparent whether it must also be at the left margin; we do this just to be
2038  * safe).  To make the related cursor movement a little faster, we use the
2039  * save/restore cursor capabilities if the terminal has them.
2040  */
2041 NCURSES_EXPORT(int)
2042 NCURSES_SP_NAME(_nc_scrolln) (NCURSES_SP_DCLx
2043                               int n,
2044                               int top,
2045                               int bot,
2046                               int maxy)
2047 /* scroll region from top to bot by n lines */
2048 {
2049     NCURSES_CH_T blank;
2050     int i;
2051     bool cursor_saved = FALSE;
2052     int res;
2053
2054     TR(TRACE_MOVE, ("_nc_scrolln(%p, %d, %d, %d, %d)",
2055                     (void *) SP_PARM, n, top, bot, maxy));
2056
2057     if (!IsValidScreen(SP_PARM))
2058         return (ERR);
2059
2060     blank = ClrBlank(NCURSES_SP_ARGx StdScreen(SP_PARM));
2061
2062 #if USE_XMC_SUPPORT
2063     /*
2064      * If we scroll, we might remove a cookie.
2065      */
2066     if (magic_cookie_glitch > 0) {
2067         return (ERR);
2068     }
2069 #endif
2070
2071     if (n > 0) {                /* scroll up (forward) */
2072         /*
2073          * Explicitly clear if stuff pushed off top of region might
2074          * be saved by the terminal.
2075          */
2076         res = scroll_csr_forward(NCURSES_SP_ARGx n, top, bot, 0, maxy, blank);
2077
2078         if (res == ERR && change_scroll_region) {
2079             if ((((n == 1 && scroll_forward) || parm_index)
2080                  && (SP_PARM->_cursrow == bot || SP_PARM->_cursrow == bot - 1))
2081                 && save_cursor && restore_cursor) {
2082                 cursor_saved = TRUE;
2083                 NCURSES_PUTP2("save_cursor", save_cursor);
2084             }
2085             NCURSES_PUTP2("change_scroll_region",
2086                           TPARM_2(change_scroll_region, top, bot));
2087             if (cursor_saved) {
2088                 NCURSES_PUTP2("restore_cursor", restore_cursor);
2089             } else {
2090                 SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2091             }
2092
2093             res = scroll_csr_forward(NCURSES_SP_ARGx n, top, bot, top, bot, blank);
2094
2095             NCURSES_PUTP2("change_scroll_region",
2096                           TPARM_2(change_scroll_region, 0, maxy));
2097             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2098         }
2099
2100         if (res == ERR && SP_PARM->_nc_sp_idlok)
2101             res = scroll_idl(NCURSES_SP_ARGx n, top, bot - n + 1, blank);
2102
2103         /*
2104          * Clear the newly shifted-in text.
2105          */
2106         if (res != ERR
2107             && (non_dest_scroll_region || (memory_below && bot == maxy))) {
2108             static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
2109             if (bot == maxy && clr_eos) {
2110                 GoTo(NCURSES_SP_ARGx bot - n + 1, 0);
2111                 ClrToEOS(NCURSES_SP_ARGx blank2);
2112             } else {
2113                 for (i = 0; i < n; i++) {
2114                     GoTo(NCURSES_SP_ARGx bot - i, 0);
2115                     ClrToEOL(NCURSES_SP_ARGx blank2, FALSE);
2116                 }
2117             }
2118         }
2119
2120     } else {                    /* (n < 0) - scroll down (backward) */
2121         res = scroll_csr_backward(NCURSES_SP_ARGx -n, top, bot, 0, maxy, blank);
2122
2123         if (res == ERR && change_scroll_region) {
2124             if (top != 0
2125                 && (SP_PARM->_cursrow == top ||
2126                     SP_PARM->_cursrow == top - 1)
2127                 && save_cursor && restore_cursor) {
2128                 cursor_saved = TRUE;
2129                 NCURSES_PUTP2("save_cursor", save_cursor);
2130             }
2131             NCURSES_PUTP2("change_scroll_region",
2132                           TPARM_2(change_scroll_region, top, bot));
2133             if (cursor_saved) {
2134                 NCURSES_PUTP2("restore_cursor", restore_cursor);
2135             } else {
2136                 SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2137             }
2138
2139             res = scroll_csr_backward(NCURSES_SP_ARGx
2140                                       -n, top, bot, top, bot, blank);
2141
2142             NCURSES_PUTP2("change_scroll_region",
2143                           TPARM_2(change_scroll_region, 0, maxy));
2144             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2145         }
2146
2147         if (res == ERR && SP_PARM->_nc_sp_idlok)
2148             res = scroll_idl(NCURSES_SP_ARGx -n, bot + n + 1, top, blank);
2149
2150         /*
2151          * Clear the newly shifted-in text.
2152          */
2153         if (res != ERR
2154             && (non_dest_scroll_region || (memory_above && top == 0))) {
2155             static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
2156             for (i = 0; i < -n; i++) {
2157                 GoTo(NCURSES_SP_ARGx i + top, 0);
2158                 ClrToEOL(NCURSES_SP_ARGx blank2, FALSE);
2159             }
2160         }
2161     }
2162
2163     if (res == ERR)
2164         return (ERR);
2165
2166     _nc_scroll_window(CurScreen(SP_PARM), n,
2167                       (NCURSES_SIZE_T) top,
2168                       (NCURSES_SIZE_T) bot,
2169                       blank);
2170
2171     /* shift hash values too - they can be reused */
2172     NCURSES_SP_NAME(_nc_scroll_oldhash) (NCURSES_SP_ARGx n, top, bot);
2173
2174     return (OK);
2175 }
2176
2177 #if NCURSES_SP_FUNCS
2178 NCURSES_EXPORT(int)
2179 _nc_scrolln(int n, int top, int bot, int maxy)
2180 {
2181     return NCURSES_SP_NAME(_nc_scrolln) (CURRENT_SCREEN, n, top, bot, maxy);
2182 }
2183 #endif
2184
2185 NCURSES_EXPORT(void)
2186 NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_DCL0)
2187 {
2188     assert(SP_PARM);
2189
2190     /* make sure terminal is in a sane known state */
2191     SetAttr(SCREEN_ATTRS(SP_PARM), A_NORMAL);
2192     NewScreen(SP_PARM)->_clear = TRUE;
2193
2194     /* reset color pairs and definitions */
2195     if (SP_PARM->_coloron || SP_PARM->_color_defs)
2196         NCURSES_SP_NAME(_nc_reset_colors) (NCURSES_SP_ARG);
2197
2198     /* restore user-defined colors, if any */
2199     if (SP_PARM->_color_defs < 0 && !SP_PARM->_direct_color.value) {
2200         int n;
2201         SP_PARM->_color_defs = -(SP_PARM->_color_defs);
2202         for (n = 0; n < SP_PARM->_color_defs; ++n) {
2203             if (SP_PARM->_color_table[n].init) {
2204                 _nc_init_color(SP_PARM,
2205                                n,
2206                                SP_PARM->_color_table[n].r,
2207                                SP_PARM->_color_table[n].g,
2208                                SP_PARM->_color_table[n].b);
2209             }
2210         }
2211     }
2212
2213     if (exit_attribute_mode)
2214         NCURSES_PUTP2("exit_attribute_mode", exit_attribute_mode);
2215     else {
2216         /* turn off attributes */
2217         if (exit_alt_charset_mode)
2218             NCURSES_PUTP2("exit_alt_charset_mode", exit_alt_charset_mode);
2219         if (exit_standout_mode)
2220             NCURSES_PUTP2("exit_standout_mode", exit_standout_mode);
2221         if (exit_underline_mode)
2222             NCURSES_PUTP2("exit_underline_mode", exit_underline_mode);
2223     }
2224     if (exit_insert_mode)
2225         NCURSES_PUTP2("exit_insert_mode", exit_insert_mode);
2226     if (enter_am_mode && exit_am_mode) {
2227         if (auto_right_margin) {
2228             NCURSES_PUTP2("enter_am_mode", enter_am_mode);
2229         } else {
2230             NCURSES_PUTP2("exit_am_mode", exit_am_mode);
2231         }
2232     }
2233 }
2234
2235 #if NCURSES_SP_FUNCS
2236 NCURSES_EXPORT(void)
2237 _nc_screen_resume(void)
2238 {
2239     NCURSES_SP_NAME(_nc_screen_resume) (CURRENT_SCREEN);
2240 }
2241 #endif
2242
2243 NCURSES_EXPORT(void)
2244 NCURSES_SP_NAME(_nc_screen_init) (NCURSES_SP_DCL0)
2245 {
2246     NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_ARG);
2247 }
2248
2249 #if NCURSES_SP_FUNCS
2250 NCURSES_EXPORT(void)
2251 _nc_screen_init(void)
2252 {
2253     NCURSES_SP_NAME(_nc_screen_init) (CURRENT_SCREEN);
2254 }
2255 #endif
2256
2257 /* wrap up screen handling */
2258 NCURSES_EXPORT(void)
2259 NCURSES_SP_NAME(_nc_screen_wrap) (NCURSES_SP_DCL0)
2260 {
2261     if (SP_PARM != 0) {
2262
2263         UpdateAttrs(SP_PARM, normal);
2264 #if NCURSES_EXT_FUNCS
2265         if (SP_PARM->_coloron
2266             && !SP_PARM->_default_color) {
2267             static const NCURSES_CH_T blank = NewChar(BLANK_TEXT);
2268             SP_PARM->_default_color = TRUE;
2269             NCURSES_SP_NAME(_nc_do_color) (NCURSES_SP_ARGx
2270                                            -1,
2271                                            0,
2272                                            FALSE,
2273                                            NCURSES_SP_NAME(_nc_outch));
2274             SP_PARM->_default_color = FALSE;
2275
2276             TINFO_MVCUR(NCURSES_SP_ARGx
2277                         SP_PARM->_cursrow,
2278                         SP_PARM->_curscol,
2279                         screen_lines(SP_PARM) - 1,
2280                         0);
2281
2282             ClrToEOL(NCURSES_SP_ARGx blank, TRUE);
2283         }
2284 #endif
2285         if (SP_PARM->_color_defs) {
2286             NCURSES_SP_NAME(_nc_reset_colors) (NCURSES_SP_ARG);
2287         }
2288     }
2289 }
2290
2291 #if NCURSES_SP_FUNCS
2292 NCURSES_EXPORT(void)
2293 _nc_screen_wrap(void)
2294 {
2295     NCURSES_SP_NAME(_nc_screen_wrap) (CURRENT_SCREEN);
2296 }
2297 #endif
2298
2299 #if USE_XMC_SUPPORT
2300 NCURSES_EXPORT(void)
2301 NCURSES_SP_NAME(_nc_do_xmc_glitch) (NCURSES_SP_DCLx attr_t previous)
2302 {
2303     if (SP_PARM != 0) {
2304         attr_t chg = XMC_CHANGES(previous ^ AttrOf(SCREEN_ATTRS(SP_PARM)));
2305
2306         while (chg != 0) {
2307             if (chg & 1) {
2308                 SP_PARM->_curscol += magic_cookie_glitch;
2309                 if (SP_PARM->_curscol >= SP_PARM->_columns)
2310                     wrap_cursor(NCURSES_SP_ARG);
2311                 TR(TRACE_UPDATE, ("bumped to %d,%d after cookie",
2312                                   SP_PARM->_cursrow, SP_PARM->_curscol));
2313             }
2314             chg >>= 1;
2315         }
2316     }
2317 }
2318
2319 #if NCURSES_SP_FUNCS
2320 NCURSES_EXPORT(void)
2321 _nc_do_xmc_glitch(attr_t previous)
2322 {
2323     NCURSES_SP_NAME(_nc_do_xmc_glitch) (CURRENT_SCREEN, previous);
2324 }
2325 #endif
2326
2327 #endif /* USE_XMC_SUPPORT */