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