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