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