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