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