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