]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tty/tty_update.c
ncurses 5.7 - patch 20090516
[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.256 2009/05/17 00:13:49 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(%d, %d) from (%d, %d)",
196                     row, col, SP_PARM->_cursrow, SP_PARM->_curscol));
197
198     position_check(SP_PARM, SP_PARM->_cursrow, SP_PARM->_curscol, "GoTo");
199
200     mvcur(SP_PARM->_cursrow, SP_PARM->_curscol, row, col);
201     position_check(SP_PARM, SP_PARM->_cursrow, SP_PARM->_curscol, "GoTo2");
202 }
203
204 static NCURSES_INLINE void
205 PutAttrChar(NCURSES_SP_DCLx CARG_CH_T ch)
206 {
207     int chlen = 1;
208     NCURSES_CH_T my_ch;
209     PUTC_DATA;
210     NCURSES_CH_T tilde;
211     NCURSES_CH_T attr = CHDEREF(ch);
212
213     TR(TRACE_CHARPUT, ("PutAttrChar(%s) at (%d, %d)",
214                        _tracech_t(ch),
215                        SP_PARM->_cursrow, SP_PARM->_curscol));
216 #if USE_WIDEC_SUPPORT
217     /*
218      * If this is not a valid character, there is nothing more to do.
219      */
220     if (isWidecExt(CHDEREF(ch))) {
221         TR(TRACE_CHARPUT, ("...skip"));
222         return;
223     }
224     /*
225      * Determine the number of character cells which the 'ch' value will use
226      * on the screen.  It should be at least one.
227      */
228     if ((chlen = wcwidth(CharOf(CHDEREF(ch)))) <= 0) {
229         static const NCURSES_CH_T blank = NewChar(BLANK_TEXT);
230
231         /*
232          * If the character falls into any of these special cases, do
233          * not force the result to a blank:
234          *
235          * a) it is printable (this works around a bug in wcwidth()).
236          * b) use_legacy_coding() has been called to modify the treatment
237          *    of codes 128-255.
238          * c) the acs_map[] has been initialized to allow codes 0-31
239          *    to be rendered.  This supports Linux console's "PC"
240          *    characters.  Codes 128-255 are allowed though this is
241          *    not checked.
242          */
243         if (is8bits(CharOf(CHDEREF(ch)))
244             && (isprint(CharOf(CHDEREF(ch)))
245                 || (SP_PARM->_legacy_coding > 0 && CharOf(CHDEREF(ch)) >= 160)
246                 || (SP_PARM->_legacy_coding > 1 && CharOf(CHDEREF(ch)) >= 128)
247                 || (AttrOf(attr) & A_ALTCHARSET
248                     && ((CharOfD(ch) < ACS_LEN
249                          && SP_PARM->_acs_map != 0
250                          && SP_PARM->_acs_map[CharOfD(ch)] != 0)
251                         || (CharOfD(ch) >= 128))))) {
252             ;
253         } else {
254             ch = CHREF(blank);
255             TR(TRACE_CHARPUT, ("forced to blank"));
256         }
257         chlen = 1;
258     }
259 #endif
260
261     if ((AttrOf(attr) & A_ALTCHARSET)
262         && SP_PARM->_acs_map != 0
263         && CharOfD(ch) < ACS_LEN) {
264         my_ch = CHDEREF(ch);    /* work around const param */
265 #if USE_WIDEC_SUPPORT
266         /*
267          * This is crude & ugly, but works most of the time.  It checks if the
268          * acs_chars string specified that we have a mapping for this
269          * character, and uses the wide-character mapping when we expect the
270          * normal one to be broken (by mis-design ;-).
271          */
272         if (SP_PARM->_screen_acs_fix
273             && SP_PARM->_screen_acs_map[CharOf(my_ch)]) {
274             RemAttr(attr, A_ALTCHARSET);
275             my_ch = _nc_wacs[CharOf(my_ch)];
276         }
277 #endif
278         /*
279          * If we (still) have alternate character set, it is the normal 8bit
280          * flavor.  The _screen_acs_map[] array tells if the character was
281          * really in acs_chars, needed because of the way wide/normal line
282          * drawing flavors are integrated.
283          */
284         if (AttrOf(attr) & A_ALTCHARSET) {
285             int j = CharOfD(ch);
286             chtype temp = UChar(SP_PARM->_acs_map[j]);
287
288             if (!(SP_PARM->_screen_acs_map[j])) {
289                 RemAttr(attr, A_ALTCHARSET);
290                 if (temp == 0)
291                     temp = ' ';
292             }
293             if (temp != 0)
294                 SetChar(my_ch, temp, AttrOf(attr));
295         }
296         ch = CHREF(my_ch);
297     }
298     if (tilde_glitch && (CharOfD(ch) == L('~'))) {
299         SetChar(tilde, L('`'), AttrOf(attr));
300         ch = CHREF(tilde);
301     }
302
303     UpdateAttrs(SP_PARM, attr);
304 #if !USE_WIDEC_SUPPORT
305     /* FIXME - we do this special case for signal handling, should see how to
306      * make it work for wide characters.
307      */
308     if (SP_PARM->_outch != 0) {
309         SP_PARM->_outch(NCURSES_SP_ARGx UChar(ch));
310     } else
311 #endif
312     {
313         PUTC(CHDEREF(ch), SP_PARM->_ofp);       /* macro's fastest... */
314         COUNT_OUTCHARS(1);
315     }
316     SP_PARM->_curscol += chlen;
317     if (char_padding) {
318         TPUTS_TRACE("char_padding");
319         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx char_padding);
320     }
321 }
322
323 static bool
324 check_pending(NCURSES_SP_DCL0)
325 /* check for pending input */
326 {
327     bool have_pending = FALSE;
328
329     /*
330      * Only carry out this check when the flag is zero, otherwise we'll
331      * have the refreshing slow down drastically (or stop) if there's an
332      * unread character available.
333      */
334     if (SP_PARM->_fifohold != 0)
335         return FALSE;
336
337     if (SP_PARM->_checkfd >= 0) {
338 #if USE_FUNC_POLL
339         struct pollfd fds[1];
340         fds[0].fd = SP_PARM->_checkfd;
341         fds[0].events = POLLIN;
342         if (poll(fds, 1, 0) > 0) {
343             have_pending = TRUE;
344         }
345 #elif defined(__BEOS__)
346         /*
347          * BeOS's select() is declared in socket.h, so the configure script does
348          * not see it.  That's just as well, since that function works only for
349          * sockets.  This (using snooze and ioctl) was distilled from Be's patch
350          * for ncurses which uses a separate thread to simulate select().
351          *
352          * FIXME: the return values from the ioctl aren't very clear if we get
353          * interrupted.
354          */
355         int n = 0;
356         int howmany = ioctl(0, 'ichr', &n);
357         if (howmany >= 0 && n > 0) {
358             have_pending = TRUE;
359         }
360 #elif HAVE_SELECT
361         fd_set fdset;
362         struct timeval ktimeout;
363
364         ktimeout.tv_sec =
365             ktimeout.tv_usec = 0;
366
367         FD_ZERO(&fdset);
368         FD_SET(SP_PARM->_checkfd, &fdset);
369         if (select(SP_PARM->_checkfd + 1, &fdset, NULL, NULL, &ktimeout) != 0) {
370             have_pending = TRUE;
371         }
372 #endif
373     }
374     if (have_pending) {
375         SP_PARM->_fifohold = 5;
376         NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
377     }
378     return FALSE;
379 }
380
381 /* put char at lower right corner */
382 static void
383 PutCharLR(NCURSES_SP_DCLx const ARG_CH_T ch)
384 {
385     if (!auto_right_margin) {
386         /* we can put the char directly */
387         PutAttrChar(NCURSES_SP_ARGx ch);
388     } else if (enter_am_mode && exit_am_mode) {
389         /* we can suppress automargin */
390         TPUTS_TRACE("exit_am_mode");
391         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_am_mode);
392
393         PutAttrChar(NCURSES_SP_ARGx ch);
394         SP_PARM->_curscol--;
395         position_check(SP_PARM,
396                        SP_PARM->_cursrow,
397                        SP_PARM->_curscol,
398                        "exit_am_mode");
399
400         TPUTS_TRACE("enter_am_mode");
401         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx enter_am_mode);
402     } else if ((enter_insert_mode && exit_insert_mode)
403                || insert_character || parm_ich) {
404         GoTo(NCURSES_SP_ARGx
405              screen_lines(SP_PARM) - 1,
406              screen_columns(SP_PARM) - 2);
407         PutAttrChar(NCURSES_SP_ARGx ch);
408         GoTo(NCURSES_SP_ARGx
409              screen_lines(SP_PARM) - 1,
410              screen_columns(SP_PARM) - 2);
411         InsStr(NCURSES_SP_ARGx
412                NewScreen(SP_PARM)->_line[screen_lines(SP_PARM) - 1].text +
413                screen_columns(SP_PARM) - 2, 1);
414     }
415 }
416
417 /*
418  * Wrap the cursor position, i.e., advance to the beginning of the next line.
419  */
420 static void
421 wrap_cursor(NCURSES_SP_DCL0)
422 {
423     if (eat_newline_glitch) {
424         /*
425          * xenl can manifest two different ways.  The vt100 way is that, when
426          * you'd expect the cursor to wrap, it stays hung at the right margin
427          * (on top of the character just emitted) and doesn't wrap until the
428          * *next* graphic char is emitted.  The c100 way is to ignore LF
429          * received just after an am wrap.
430          *
431          * An aggressive way to handle this would be to emit CR/LF after the
432          * char and then assume the wrap is done, you're on the first position
433          * of the next line, and the terminal out of its weird state.  Here
434          * it's safe to just tell the code that the cursor is in hyperspace and
435          * let the next mvcur() call straighten things out.
436          */
437         SP_PARM->_curscol = -1;
438         SP_PARM->_cursrow = -1;
439     } else if (auto_right_margin) {
440         SP_PARM->_curscol = 0;
441         SP_PARM->_cursrow++;
442         /*
443          * We've actually moved - but may have to work around problems with
444          * video attributes not working.
445          */
446         if (!move_standout_mode && AttrOf(SCREEN_ATTRS(SP_PARM))) {
447             TR(TRACE_CHARPUT, ("turning off (%#lx) %s before wrapping",
448                                (unsigned long) AttrOf(SCREEN_ATTRS(SP_PARM)),
449                                _traceattr(AttrOf(SCREEN_ATTRS(SP_PARM)))));
450             (void) VIDATTR(SP_PARM, A_NORMAL, 0);
451         }
452     } else {
453         SP_PARM->_curscol--;
454     }
455     position_check(SP_PARM,
456                    SP_PARM->_cursrow,
457                    SP_PARM->_curscol,
458                    "wrap_cursor");
459 }
460
461 static NCURSES_INLINE void
462 PutChar(NCURSES_SP_DCLx const ARG_CH_T ch)
463 /* insert character, handling automargin stuff */
464 {
465     if (SP_PARM->_cursrow == screen_lines(SP_PARM) - 1 &&
466         SP_PARM->_curscol == screen_columns(SP_PARM) - 1) {
467         PutCharLR(NCURSES_SP_ARGx ch);
468     } else {
469         PutAttrChar(NCURSES_SP_ARGx ch);
470     }
471
472     if (SP_PARM->_curscol >= screen_columns(SP_PARM))
473         wrap_cursor(NCURSES_SP_ARG);
474
475     position_check(SP_PARM, SP_PARM->_cursrow, SP_PARM->_curscol, "PutChar");
476 }
477
478 /*
479  * Check whether the given character can be output by clearing commands.  This
480  * includes test for being a space and not including any 'bad' attributes, such
481  * as A_REVERSE.  All attribute flags which don't affect appearance of a space
482  * or can be output by clearing (A_COLOR in case of bce-terminal) are excluded.
483  */
484 static NCURSES_INLINE bool
485 can_clear_with(NCURSES_SP_DCLx ARG_CH_T ch)
486 {
487     if (!back_color_erase && SP_PARM->_coloron) {
488 #if NCURSES_EXT_FUNCS
489         int pair;
490
491         if (!SP_PARM->_default_color)
492             return FALSE;
493         if (SP_PARM->_default_fg != C_MASK || SP_PARM->_default_bg != C_MASK)
494             return FALSE;
495         if ((pair = GetPair(CHDEREF(ch))) != 0) {
496             short fg, bg;
497             NCURSES_SP_NAME(pair_content) (NCURSES_SP_ARGx pair, &fg, &bg);
498             if (fg != C_MASK || bg != C_MASK)
499                 return FALSE;
500         }
501 #else
502         if (AttrOfD(ch) & A_COLOR)
503             return FALSE;
504 #endif
505     }
506     return (ISBLANK(CHDEREF(ch)) &&
507             (AttrOfD(ch) & ~(NONBLANK_ATTR | A_COLOR)) == BLANK_ATTR);
508 }
509
510 /*
511  * Issue a given span of characters from an array.
512  * Must be functionally equivalent to:
513  *      for (i = 0; i < num; i++)
514  *          PutChar(ntext[i]);
515  * but can leave the cursor positioned at the middle of the interval.
516  *
517  * Returns: 0 - cursor is at the end of interval
518  *          1 - cursor is somewhere in the middle
519  *
520  * This code is optimized using ech and rep.
521  */
522 static int
523 EmitRange(NCURSES_SP_DCLx const NCURSES_CH_T * ntext, int num)
524 {
525     int i;
526
527     TR(TRACE_CHARPUT, ("EmitRange %d:%s", num, _nc_viscbuf(ntext, num)));
528
529     if (erase_chars || repeat_char) {
530         while (num > 0) {
531             int runcount;
532             NCURSES_CH_T ntext0;
533
534             while (num > 1 && !CharEq(ntext[0], ntext[1])) {
535                 PutChar(NCURSES_SP_ARGx CHREF(ntext[0]));
536                 ntext++;
537                 num--;
538             }
539             ntext0 = ntext[0];
540             if (num == 1) {
541                 PutChar(NCURSES_SP_ARGx CHREF(ntext0));
542                 return 0;
543             }
544             runcount = 2;
545
546             while (runcount < num && CharEq(ntext[runcount], ntext0))
547                 runcount++;
548
549             /*
550              * The cost expression in the middle isn't exactly right.
551              * _cup_ch_cost is an upper bound on the cost for moving to the
552              * end of the erased area, but not the cost itself (which we
553              * can't compute without emitting the move).  This may result
554              * in erase_chars not getting used in some situations for
555              * which it would be marginally advantageous.
556              */
557             if (erase_chars
558                 && runcount > SP_PARM->_ech_cost + SP_PARM->_cup_ch_cost
559                 && can_clear_with(NCURSES_SP_ARGx CHREF(ntext0))) {
560                 UpdateAttrs(SP_PARM, ntext0);
561                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx TPARM_1(erase_chars, runcount));
562
563                 /*
564                  * If this is the last part of the given interval,
565                  * don't bother moving cursor, since it can be the
566                  * last update on the line.
567                  */
568                 if (runcount < num) {
569                     GoTo(NCURSES_SP_ARGx
570                          SP_PARM->_cursrow,
571                          SP_PARM->_curscol + runcount);
572                 } else {
573                     return 1;   /* cursor stays in the middle */
574                 }
575             } else if (repeat_char && runcount > SP_PARM->_rep_cost) {
576                 bool wrap_possible = (SP_PARM->_curscol + runcount >=
577                                       screen_columns(SP_PARM));
578                 int rep_count = runcount;
579
580                 if (wrap_possible)
581                     rep_count--;
582
583                 UpdateAttrs(SP_PARM, ntext0);
584                 NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
585                                         TPARM_2(repeat_char,
586                                                 CharOf(ntext0),
587                                                 rep_count),
588                                         rep_count,
589                                         NCURSES_SP_NAME(_nc_outch));
590                 SP_PARM->_curscol += rep_count;
591
592                 if (wrap_possible)
593                     PutChar(NCURSES_SP_ARGx CHREF(ntext0));
594             } else {
595                 for (i = 0; i < runcount; i++)
596                     PutChar(NCURSES_SP_ARGx CHREF(ntext[i]));
597             }
598             ntext += runcount;
599             num -= runcount;
600         }
601         return 0;
602     }
603
604     for (i = 0; i < num; i++)
605         PutChar(NCURSES_SP_ARGx CHREF(ntext[i]));
606     return 0;
607 }
608
609 /*
610  * Output the line in the given range [first .. last]
611  *
612  * If there's a run of identical characters that's long enough to justify
613  * cursor movement, use that also.
614  *
615  * Returns: same as EmitRange
616  */
617 static int
618 PutRange(NCURSES_SP_DCLx
619          const NCURSES_CH_T * otext,
620          const NCURSES_CH_T * ntext,
621          int row,
622          int first, int last)
623 {
624     int i, j, same;
625
626     TR(TRACE_CHARPUT, ("PutRange(%p, %p, %p, %d, %d, %d)",
627                        SP_PARM, otext, ntext, row, first, last));
628
629     if (otext != ntext
630         && (last - first + 1) > SP_PARM->_inline_cost) {
631         for (j = first, same = 0; j <= last; j++) {
632             if (!same && isWidecExt(otext[j]))
633                 continue;
634             if (CharEq(otext[j], ntext[j])) {
635                 same++;
636             } else {
637                 if (same > SP_PARM->_inline_cost) {
638                     EmitRange(NCURSES_SP_ARGx ntext + first, j - same - first);
639                     GoTo(NCURSES_SP_ARGx row, first = j);
640                 }
641                 same = 0;
642             }
643         }
644         i = EmitRange(NCURSES_SP_ARGx ntext + first, j - same - first);
645         /*
646          * Always return 1 for the next GoTo() after a PutRange() if we found
647          * identical characters at end of interval
648          */
649         return (same == 0 ? i : 1);
650     }
651     return EmitRange(NCURSES_SP_ARGx ntext + first, last - first + 1);
652 }
653
654 /* leave unbracketed here so 'indent' works */
655 #define MARK_NOCHANGE(win,row) \
656                 win->_line[row].firstchar = _NOCHANGE; \
657                 win->_line[row].lastchar = _NOCHANGE; \
658                 if_USE_SCROLL_HINTS(win->_line[row].oldindex = row)
659
660 NCURSES_EXPORT(int)
661 NCURSES_SP_NAME(doupdate) (NCURSES_SP_DCL0)
662 {
663     int i;
664     int nonempty;
665 #if USE_TRACE_TIMES
666     struct tms before, after;
667 #endif /* USE_TRACE_TIMES */
668
669     T((T_CALLED("doupdate()")));
670
671 #if !USE_REENTRANT
672     /*
673      * It is "legal" but unlikely that an application could assign a new
674      * value to one of the standard windows.  Check for that possibility
675      * and try to recover.
676      *
677      * We do not allow applications to assign new values in the reentrant
678      * model.
679      */
680 #define SyncScreens(internal,exported) \
681         if (internal == 0) internal = exported; \
682         if (internal != exported) exported = internal
683
684     SyncScreens(CurScreen(SP_PARM), curscr);
685     SyncScreens(NewScreen(SP_PARM), newscr);
686     SyncScreens(StdScreen(SP_PARM), stdscr);
687 #endif
688
689     if (CurScreen(SP_PARM) == 0
690         || NewScreen(SP_PARM) == 0
691         || StdScreen(SP_PARM) == 0)
692         returnCode(ERR);
693
694 #ifdef TRACE
695     if (USE_TRACEF(TRACE_UPDATE)) {
696         if (CurScreen(SP_PARM)->_clear)
697             _tracef("curscr is clear");
698         else
699             _tracedump("curscr", CurScreen(SP_PARM));
700         _tracedump("newscr", NewScreen(SP_PARM));
701         _nc_unlock_global(tracef);
702     }
703 #endif /* TRACE */
704
705     _nc_signal_handler(FALSE);
706
707     if (SP_PARM->_fifohold)
708         SP_PARM->_fifohold--;
709
710 #if USE_SIZECHANGE
711     if (SP_PARM->_endwin || _nc_handle_sigwinch(SP_PARM)) {
712         /*
713          * This is a transparent extension:  XSI does not address it,
714          * and applications need not know that ncurses can do it.
715          *
716          * Check if the terminal size has changed while curses was off
717          * (this can happen in an xterm, for example), and resize the
718          * ncurses data structures accordingly.
719          */
720         _nc_update_screensize(SP_PARM);
721     }
722 #endif
723
724     if (SP_PARM->_endwin) {
725
726         T(("coming back from shell mode"));
727         NCURSES_SP_NAME(reset_prog_mode) (NCURSES_SP_ARG);
728
729         NCURSES_SP_NAME(_nc_mvcur_resume) (NCURSES_SP_ARG);
730         NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_ARG);
731         SP_PARM->_mouse_resume(SP_PARM);
732
733         SP_PARM->_endwin = FALSE;
734     }
735 #if USE_TRACE_TIMES
736     /* zero the metering machinery */
737     RESET_OUTCHARS();
738     (void) times(&before);
739 #endif /* USE_TRACE_TIMES */
740
741     /*
742      * This is the support for magic-cookie terminals.  The theory:  we scan
743      * the virtual screen looking for attribute turnons.  Where we find one,
744      * check to make sure it's realizable by seeing if the required number of
745      * un-attributed blanks are present before and after the attributed range;
746      * try to shift the range boundaries over blanks (not changing the screen
747      * display) so this becomes true.  If it is, shift the beginning attribute
748      * change appropriately (the end one, if we've gotten this far, is
749      * guaranteed room for its cookie).  If not, nuke the added attributes out
750      * of the span.
751      */
752 #if USE_XMC_SUPPORT
753     if (magic_cookie_glitch > 0) {
754         int j, k;
755         attr_t rattr = A_NORMAL;
756
757         for (i = 0; i < screen_lines(SP_PARM); i++) {
758             for (j = 0; j < screen_columns(SP_PARM); j++) {
759                 bool failed = FALSE;
760                 NCURSES_CH_T *thisline = NewScreen(SP_PARM)->_line[i].text;
761                 attr_t thisattr = AttrOf(thisline[j]) & SP_PARM->_xmc_triggers;
762                 attr_t turnon = thisattr & ~rattr;
763
764                 /* is an attribute turned on here? */
765                 if (turnon == 0) {
766                     rattr = thisattr;
767                     continue;
768                 }
769
770                 TR(TRACE_ATTRS, ("At (%d, %d): from %s...", i, j, _traceattr(rattr)));
771                 TR(TRACE_ATTRS, ("...to %s", _traceattr(turnon)));
772
773                 /*
774                  * If the attribute change location is a blank with a "safe"
775                  * attribute, undo the attribute turnon.  This may ensure
776                  * there's enough room to set the attribute before the first
777                  * non-blank in the run.
778                  */
779 #define SAFE(scr,a)     (!((a) & (scr)->_xmc_triggers))
780                 if (ISBLANK(thisline[j]) && SAFE(SP_PARM, turnon)) {
781                     RemAttr(thisline[j], turnon);
782                     continue;
783                 }
784
785                 /* check that there's enough room at start of span */
786                 for (k = 1; k <= magic_cookie_glitch; k++) {
787                     if (j - k < 0
788                         || !ISBLANK(thisline[j - k])
789                         || !SAFE(SP_PARM, AttrOf(thisline[j - k]))) {
790                         failed = TRUE;
791                         TR(TRACE_ATTRS, ("No room at start in %d,%d%s%s",
792                                          i, j - k,
793                                          (ISBLANK(thisline[j - k])
794                                           ? ""
795                                           : ":nonblank"),
796                                          (SAFE(SP_PARM, AttrOf(thisline[j - k]))
797                                           ? ""
798                                           : ":unsafe")));
799                         break;
800                     }
801                 }
802                 if (!failed) {
803                     bool end_onscreen = FALSE;
804                     int m, n = j;
805
806                     /* find end of span, if it's onscreen */
807                     for (m = i; m < screen_lines(SP_PARM); m++) {
808                         for (; n < screen_columns(SP_PARM); n++) {
809                             attr_t testattr
810                             = AttrOf(NewScreen(SP_PARM)->_line[m].text[n]);
811
812                             if ((testattr & SP_PARM->_xmc_triggers) == rattr) {
813                                 end_onscreen = TRUE;
814                                 TR(TRACE_ATTRS,
815                                    ("Range attributed with %s ends at (%d, %d)",
816                                     _traceattr(turnon), m, n));
817                                 goto foundit;
818                             }
819                         }
820                         n = 0;
821                     }
822                     TR(TRACE_ATTRS,
823                        ("Range attributed with %s ends offscreen",
824                         _traceattr(turnon)));
825                   foundit:;
826
827                     if (end_onscreen) {
828                         NCURSES_CH_T *lastline =
829                         NewScreen(SP_PARM)->_line[m].text;
830
831                         /*
832                          * If there are safely-attributed blanks at the end of
833                          * the range, shorten the range.  This will help ensure
834                          * that there is enough room at end of span.
835                          */
836                         while (n >= 0
837                                && ISBLANK(lastline[n])
838                                && SAFE(SP_PARM, AttrOf(lastline[n]))) {
839                             RemAttr(lastline[n--], turnon);
840                         }
841
842                         /* check that there's enough room at end of span */
843                         for (k = 1; k <= magic_cookie_glitch; k++) {
844                             if (n + k >= screen_columns(SP_PARM)
845                                 || !ISBLANK(lastline[n + k])
846                                 || !SAFE(SP_PARM, AttrOf(lastline[n + k]))) {
847                                 failed = TRUE;
848                                 TR(TRACE_ATTRS,
849                                    ("No room at end in %d,%d%s%s",
850                                     i, j - k,
851                                     (ISBLANK(lastline[n + k])
852                                      ? ""
853                                      : ":nonblank"),
854                                     (SAFE(SP_PARM, AttrOf(lastline[n + k]))
855                                      ? ""
856                                      : ":unsafe")));
857                                 break;
858                             }
859                         }
860                     }
861                 }
862
863                 if (failed) {
864                     int p, q = j;
865
866                     TR(TRACE_ATTRS,
867                        ("Clearing %s beginning at (%d, %d)",
868                         _traceattr(turnon), i, j));
869
870                     /* turn off new attributes over span */
871                     for (p = i; p < screen_lines(SP_PARM); p++) {
872                         for (; q < screen_columns(SP_PARM); q++) {
873                             attr_t testattr =
874                             AttrOf(NewScreen(SP_PARM)->_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             _nc_scroll_optimize();
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(win) (((win) == CurScreen(SP_PARM) ? StdScreen(SP_PARM) : (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(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 (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_PARM)->_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 CurScreen(SP_PARM)),
1275                  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                        || !(_nc_idcok && has_ic()))) {
1436             GoTo(NCURSES_SP_ARGx lineno, firstChar);
1437             if ((oLastChar - nLastChar) > SP_PARM->_el_cost) {
1438                 if (PutRange(NCURSES_SP_ARGx
1439                              oldLine,
1440                              newLine,
1441                              lineno,
1442                              firstChar,
1443                              nLastChar)) {
1444                     GoTo(NCURSES_SP_ARGx lineno, nLastChar + 1);
1445                 }
1446                 ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1447             } else {
1448                 n = max(nLastChar, oLastChar);
1449                 PutRange(NCURSES_SP_ARGx
1450                          oldLine,
1451                          newLine,
1452                          lineno,
1453                          firstChar,
1454                          n);
1455             }
1456         } else {
1457             int nLastNonblank = nLastChar;
1458             int oLastNonblank = oLastChar;
1459
1460             /* find the last characters that really differ */
1461             /* can be -1 if no characters differ */
1462             while (CharEq(newLine[nLastChar], oldLine[oLastChar])) {
1463                 /* don't split a wide char */
1464                 if (isWidecExt(newLine[nLastChar]) &&
1465                     !CharEq(newLine[nLastChar - 1], oldLine[oLastChar - 1]))
1466                     break;
1467                 nLastChar--;
1468                 oLastChar--;
1469                 if (nLastChar == -1 || oLastChar == -1)
1470                     break;
1471             }
1472
1473             n = min(oLastChar, nLastChar);
1474             if (n >= firstChar) {
1475                 GoTo(NCURSES_SP_ARGx lineno, firstChar);
1476                 PutRange(NCURSES_SP_ARGx
1477                          oldLine,
1478                          newLine,
1479                          lineno,
1480                          firstChar,
1481                          n);
1482             }
1483
1484             if (oLastChar < nLastChar) {
1485                 int m = max(nLastNonblank, oLastNonblank);
1486 #if USE_WIDEC_SUPPORT
1487                 while (isWidecExt(newLine[n + 1]) && n) {
1488                     --n;
1489                     --oLastChar;
1490                 }
1491 #endif
1492                 GoTo(NCURSES_SP_ARGx lineno, n + 1);
1493                 if ((nLastChar < nLastNonblank)
1494                     || InsCharCost(SP_PARM, nLastChar - oLastChar) > (m - n)) {
1495                     PutRange(NCURSES_SP_ARGx
1496                              oldLine,
1497                              newLine,
1498                              lineno,
1499                              n + 1,
1500                              m);
1501                 } else {
1502                     InsStr(NCURSES_SP_ARGx &newLine[n + 1], nLastChar - oLastChar);
1503                 }
1504             } else if (oLastChar > nLastChar) {
1505                 GoTo(NCURSES_SP_ARGx lineno, n + 1);
1506                 if (DelCharCost(SP_PARM, oLastChar - nLastChar)
1507                     > SP_PARM->_el_cost + nLastNonblank - (n + 1)) {
1508                     if (PutRange(NCURSES_SP_ARGx oldLine, newLine, lineno,
1509                                  n + 1, nLastNonblank))
1510                           GoTo(NCURSES_SP_ARGx lineno, nLastNonblank + 1);
1511                     ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1512                 } else {
1513                     /*
1514                      * The delete-char sequence will
1515                      * effectively shift in blanks from the
1516                      * right margin of the screen.  Ensure
1517                      * that they are the right color by
1518                      * setting the video attributes from
1519                      * the last character on the row.
1520                      */
1521                     UpdateAttrs(SP_PARM, blank);
1522                     DelChar(NCURSES_SP_ARGx oLastChar - nLastChar);
1523                 }
1524             }
1525         }
1526     }
1527
1528     /* update the code's internal representation */
1529     if (screen_columns(SP_PARM) > firstChar)
1530         memcpy(oldLine + firstChar,
1531                newLine + firstChar,
1532                (screen_columns(SP_PARM) - firstChar) * sizeof(NCURSES_CH_T));
1533     TR(TRACE_UPDATE, (T_RETURN("")));
1534     return;
1535 }
1536
1537 /*
1538 **      ClearScreen(blank)
1539 **
1540 **      Clear the physical screen and put cursor at home
1541 **
1542 */
1543
1544 static void
1545 ClearScreen(NCURSES_SP_DCLx NCURSES_CH_T blank)
1546 {
1547     int i, j;
1548     bool fast_clear = (clear_screen || clr_eos || clr_eol);
1549
1550     TR(TRACE_UPDATE, ("ClearScreen() called"));
1551
1552 #if NCURSES_EXT_FUNCS
1553     if (SP_PARM->_coloron
1554         && !SP_PARM->_default_color) {
1555         NCURSES_SP_NAME(_nc_do_color) (NCURSES_SP_ARGx
1556                                        GET_SCREEN_PAIR(SP_PARM),
1557                                        0,
1558                                        FALSE,
1559                                        NCURSES_SP_NAME(_nc_outch));
1560         if (!back_color_erase) {
1561             fast_clear = FALSE;
1562         }
1563     }
1564 #endif
1565
1566     if (fast_clear) {
1567         if (clear_screen) {
1568             UpdateAttrs(SP_PARM, blank);
1569             TPUTS_TRACE("clear_screen");
1570             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clear_screen);
1571             SP_PARM->_cursrow = SP_PARM->_curscol = 0;
1572             position_check(SP_PARM,
1573                            SP_PARM->_cursrow,
1574                            SP_PARM->_curscol,
1575                            "ClearScreen");
1576         } else if (clr_eos) {
1577             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1578             GoTo(NCURSES_SP_ARGx 0, 0);
1579
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
1589             UpdateAttrs(SP_PARM, blank);
1590             for (i = 0; i < screen_lines(SP_PARM); i++) {
1591                 GoTo(NCURSES_SP_ARGx i, 0);
1592                 TPUTS_TRACE("clr_eol");
1593                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clr_eol);
1594             }
1595             GoTo(NCURSES_SP_ARGx 0, 0);
1596         }
1597     } else {
1598         UpdateAttrs(SP_PARM, blank);
1599         for (i = 0; i < screen_lines(SP_PARM); i++) {
1600             GoTo(NCURSES_SP_ARGx i, 0);
1601             for (j = 0; j < screen_columns(SP_PARM); j++)
1602                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1603         }
1604         GoTo(NCURSES_SP_ARGx 0, 0);
1605     }
1606
1607     for (i = 0; i < screen_lines(SP_PARM); i++) {
1608         for (j = 0; j < screen_columns(SP_PARM); j++)
1609             CurScreen(SP_PARM)->_line[i].text[j] = blank;
1610     }
1611
1612     TR(TRACE_UPDATE, ("screen cleared"));
1613 }
1614
1615 /*
1616 **      InsStr(line, count)
1617 **
1618 **      Insert the count characters pointed to by line.
1619 **
1620 */
1621
1622 static void
1623 InsStr(NCURSES_SP_DCLx NCURSES_CH_T * line, int count)
1624 {
1625     TR(TRACE_UPDATE, ("InsStr(%p, %p,%d) called", SP_PARM, line, count));
1626
1627     /* Prefer parm_ich as it has the smallest cost - no need to shift
1628      * the whole line on each character. */
1629     /* The order must match that of InsCharCost. */
1630     if (parm_ich) {
1631         TPUTS_TRACE("parm_ich");
1632         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1633                                 TPARM_1(parm_ich, count),
1634                                 count,
1635                                 NCURSES_SP_NAME(_nc_outch));
1636         while (count) {
1637             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1638             line++;
1639             count--;
1640         }
1641     } else if (enter_insert_mode && exit_insert_mode) {
1642         TPUTS_TRACE("enter_insert_mode");
1643         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx enter_insert_mode);
1644         while (count) {
1645             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1646             if (insert_padding) {
1647                 TPUTS_TRACE("insert_padding");
1648                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_padding);
1649             }
1650             line++;
1651             count--;
1652         }
1653         TPUTS_TRACE("exit_insert_mode");
1654         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_insert_mode);
1655     } else {
1656         while (count) {
1657             TPUTS_TRACE("insert_character");
1658             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_character);
1659             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1660             if (insert_padding) {
1661                 TPUTS_TRACE("insert_padding");
1662                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_padding);
1663             }
1664             line++;
1665             count--;
1666         }
1667     }
1668     position_check(SP_PARM, SP_PARM->_cursrow, SP_PARM->_curscol, "InsStr");
1669 }
1670
1671 /*
1672 **      DelChar(count)
1673 **
1674 **      Delete count characters at current position
1675 **
1676 */
1677
1678 static void
1679 DelChar(NCURSES_SP_DCLx int count)
1680 {
1681     int n;
1682
1683     TR(TRACE_UPDATE, ("DelChar(%p, %d) called, position = (%ld,%ld)",
1684                       SP_PARM, count,
1685                       (long) NewScreen(SP_PARM)->_cury,
1686                       (long) NewScreen(SP_PARM)->_curx));
1687
1688     if (parm_dch) {
1689         TPUTS_TRACE("parm_dch");
1690         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1691                                 TPARM_1(parm_dch, count),
1692                                 count,
1693                                 NCURSES_SP_NAME(_nc_outch));
1694     } else {
1695         for (n = 0; n < count; n++) {
1696             TPUTS_TRACE("delete_character");
1697             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_character);
1698         }
1699     }
1700 }
1701
1702 /*
1703  * Physical-scrolling support
1704  *
1705  * This code was adapted from Keith Bostic's hardware scrolling
1706  * support for 4.4BSD curses.  I (esr) translated it to use terminfo
1707  * capabilities, narrowed the call interface slightly, and cleaned
1708  * up some convoluted tests.  I also added support for the memory_above
1709  * memory_below, and non_dest_scroll_region capabilities.
1710  *
1711  * For this code to work, we must have either
1712  * change_scroll_region and scroll forward/reverse commands, or
1713  * insert and delete line capabilities.
1714  * When the scrolling region has been set, the cursor has to
1715  * be at the last line of the region to make the scroll up
1716  * happen, or on the first line of region to scroll down.
1717  *
1718  * This code makes one aesthetic decision in the opposite way from
1719  * BSD curses.  BSD curses preferred pairs of il/dl operations
1720  * over scrolls, allegedly because il/dl looked faster.  We, on
1721  * the other hand, prefer scrolls because (a) they're just as fast
1722  * on many terminals and (b) using them avoids bouncing an
1723  * unchanged bottom section of the screen up and down, which is
1724  * visually nasty.
1725  *
1726  * (lav): added more cases, used dl/il when bot==maxy and in csr case.
1727  *
1728  * I used assumption that capabilities il/il1/dl/dl1 work inside
1729  * changed scroll region not shifting screen contents outside of it.
1730  * If there are any terminals behaving different way, it would be
1731  * necessary to add some conditions to scroll_csr_forward/backward.
1732  */
1733
1734 /* Try to scroll up assuming given csr (miny, maxy). Returns ERR on failure */
1735 static int
1736 scroll_csr_forward(NCURSES_SP_DCLx
1737                    int n,
1738                    int top,
1739                    int bot,
1740                    int miny,
1741                    int maxy,
1742                    NCURSES_CH_T blank)
1743 {
1744     int i;
1745
1746     if (n == 1 && scroll_forward && top == miny && bot == maxy) {
1747         GoTo(NCURSES_SP_ARGx bot, 0);
1748         UpdateAttrs(SP_PARM, blank);
1749         TPUTS_TRACE("scroll_forward");
1750         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_forward);
1751     } else if (n == 1 && delete_line && bot == maxy) {
1752         GoTo(NCURSES_SP_ARGx top, 0);
1753         UpdateAttrs(SP_PARM, blank);
1754         TPUTS_TRACE("delete_line");
1755         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1756     } else if (parm_index && top == miny && bot == maxy) {
1757         GoTo(NCURSES_SP_ARGx bot, 0);
1758         UpdateAttrs(SP_PARM, blank);
1759         TPUTS_TRACE("parm_index");
1760         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1761                                 TPARM_2(parm_index, n, 0),
1762                                 n,
1763                                 NCURSES_SP_NAME(_nc_outch));
1764     } else if (parm_delete_line && bot == maxy) {
1765         GoTo(NCURSES_SP_ARGx top, 0);
1766         UpdateAttrs(SP_PARM, blank);
1767         TPUTS_TRACE("parm_delete_line");
1768         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1769                                 TPARM_2(parm_delete_line, n, 0),
1770                                 n,
1771                                 NCURSES_SP_NAME(_nc_outch));
1772     } else if (scroll_forward && top == miny && bot == maxy) {
1773         GoTo(NCURSES_SP_ARGx bot, 0);
1774         UpdateAttrs(SP_PARM, blank);
1775         for (i = 0; i < n; i++) {
1776             TPUTS_TRACE("scroll_forward");
1777             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_forward);
1778         }
1779     } else if (delete_line && bot == maxy) {
1780         GoTo(NCURSES_SP_ARGx top, 0);
1781         UpdateAttrs(SP_PARM, blank);
1782         for (i = 0; i < n; i++) {
1783             TPUTS_TRACE("delete_line");
1784             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1785         }
1786     } else
1787         return ERR;
1788
1789 #if NCURSES_EXT_FUNCS
1790     if (FILL_BCE(SP_PARM)) {
1791         int j;
1792         for (i = 0; i < n; i++) {
1793             GoTo(NCURSES_SP_ARGx bot - i, 0);
1794             for (j = 0; j < screen_columns(SP_PARM); j++)
1795                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1796         }
1797     }
1798 #endif
1799     return OK;
1800 }
1801
1802 /* Try to scroll down assuming given csr (miny, maxy). Returns ERR on failure */
1803 /* n > 0 */
1804 static int
1805 scroll_csr_backward(NCURSES_SP_DCLx
1806                     int n,
1807                     int top,
1808                     int bot,
1809                     int miny,
1810                     int maxy,
1811                     NCURSES_CH_T blank)
1812 {
1813     int i;
1814
1815     if (n == 1 && scroll_reverse && top == miny && bot == maxy) {
1816         GoTo(NCURSES_SP_ARGx top, 0);
1817         UpdateAttrs(SP_PARM, blank);
1818         TPUTS_TRACE("scroll_reverse");
1819         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_reverse);
1820     } else if (n == 1 && insert_line && bot == maxy) {
1821         GoTo(NCURSES_SP_ARGx top, 0);
1822         UpdateAttrs(SP_PARM, blank);
1823         TPUTS_TRACE("insert_line");
1824         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1825     } else if (parm_rindex && top == miny && bot == maxy) {
1826         GoTo(NCURSES_SP_ARGx top, 0);
1827         UpdateAttrs(SP_PARM, blank);
1828         TPUTS_TRACE("parm_rindex");
1829         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1830                                 TPARM_2(parm_rindex, n, 0),
1831                                 n,
1832                                 NCURSES_SP_NAME(_nc_outch));
1833     } else if (parm_insert_line && bot == maxy) {
1834         GoTo(NCURSES_SP_ARGx top, 0);
1835         UpdateAttrs(SP_PARM, blank);
1836         TPUTS_TRACE("parm_insert_line");
1837         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1838                                 TPARM_2(parm_insert_line, n, 0),
1839                                 n,
1840                                 NCURSES_SP_NAME(_nc_outch));
1841     } else if (scroll_reverse && top == miny && bot == maxy) {
1842         GoTo(NCURSES_SP_ARGx top, 0);
1843         UpdateAttrs(SP_PARM, blank);
1844         for (i = 0; i < n; i++) {
1845             TPUTS_TRACE("scroll_reverse");
1846             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_reverse);
1847         }
1848     } else if (insert_line && bot == maxy) {
1849         GoTo(NCURSES_SP_ARGx top, 0);
1850         UpdateAttrs(SP_PARM, blank);
1851         for (i = 0; i < n; i++) {
1852             TPUTS_TRACE("insert_line");
1853             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1854         }
1855     } else
1856         return ERR;
1857
1858 #if NCURSES_EXT_FUNCS
1859     if (FILL_BCE(SP_PARM)) {
1860         int j;
1861         for (i = 0; i < n; i++) {
1862             GoTo(NCURSES_SP_ARGx top + i, 0);
1863             for (j = 0; j < screen_columns(SP_PARM); j++)
1864                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1865         }
1866     }
1867 #endif
1868     return OK;
1869 }
1870
1871 /* scroll by using delete_line at del and insert_line at ins */
1872 /* n > 0 */
1873 static int
1874 scroll_idl(NCURSES_SP_DCLx int n, int del, int ins, NCURSES_CH_T blank)
1875 {
1876     int i;
1877
1878     if (!((parm_delete_line || delete_line) && (parm_insert_line || insert_line)))
1879         return ERR;
1880
1881     GoTo(NCURSES_SP_ARGx del, 0);
1882     UpdateAttrs(SP_PARM, blank);
1883     if (n == 1 && delete_line) {
1884         TPUTS_TRACE("delete_line");
1885         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1886     } else if (parm_delete_line) {
1887         TPUTS_TRACE("parm_delete_line");
1888         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1889                                 TPARM_2(parm_delete_line, n, 0),
1890                                 n,
1891                                 NCURSES_SP_NAME(_nc_outch));
1892     } else {                    /* if (delete_line) */
1893         for (i = 0; i < n; i++) {
1894             TPUTS_TRACE("delete_line");
1895             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1896         }
1897     }
1898
1899     GoTo(NCURSES_SP_ARGx ins, 0);
1900     UpdateAttrs(SP_PARM, blank);
1901     if (n == 1 && insert_line) {
1902         TPUTS_TRACE("insert_line");
1903         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1904     } else if (parm_insert_line) {
1905         TPUTS_TRACE("parm_insert_line");
1906         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1907                                 TPARM_2(parm_insert_line, n, 0),
1908                                 n,
1909                                 NCURSES_SP_NAME(_nc_outch));
1910     } else {                    /* if (insert_line) */
1911         for (i = 0; i < n; i++) {
1912             TPUTS_TRACE("insert_line");
1913             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1914         }
1915     }
1916
1917     return OK;
1918 }
1919
1920 /*
1921  * Note:  some terminals require the cursor to be within the scrolling margins
1922  * before setting them.  Generally, the cursor must be at the appropriate end
1923  * of the scrolling margins when issuing an indexing operation (it is not
1924  * apparent whether it must also be at the left margin; we do this just to be
1925  * safe).  To make the related cursor movement a little faster, we use the
1926  * save/restore cursor capabilities if the terminal has them.
1927  */
1928 NCURSES_EXPORT(int)
1929 NCURSES_SP_NAME(_nc_scrolln) (NCURSES_SP_DCLx
1930                               int n,
1931                               int top,
1932                               int bot,
1933                               int maxy)
1934 /* scroll region from top to bot by n lines */
1935 {
1936     NCURSES_CH_T blank = ClrBlank(NCURSES_SP_ARGx StdScreen(SP_PARM));
1937     int i;
1938     bool cursor_saved = FALSE;
1939     int res;
1940
1941     TR(TRACE_MOVE, ("mvcur_scrolln(%d, %d, %d, %d)", n, top, bot, maxy));
1942
1943 #if USE_XMC_SUPPORT
1944     /*
1945      * If we scroll, we might remove a cookie.
1946      */
1947     if (magic_cookie_glitch > 0) {
1948         return (ERR);
1949     }
1950 #endif
1951
1952     if (n > 0) {                /* scroll up (forward) */
1953         /*
1954          * Explicitly clear if stuff pushed off top of region might
1955          * be saved by the terminal.
1956          */
1957         res = scroll_csr_forward(NCURSES_SP_ARGx n, top, bot, 0, maxy, blank);
1958
1959         if (res == ERR && change_scroll_region) {
1960             if ((((n == 1 && scroll_forward) || parm_index)
1961                  && (SP_PARM->_cursrow == bot || SP_PARM->_cursrow == bot - 1))
1962                 && save_cursor && restore_cursor) {
1963                 cursor_saved = TRUE;
1964                 TPUTS_TRACE("save_cursor");
1965                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx save_cursor);
1966             }
1967             TPUTS_TRACE("change_scroll_region");
1968             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
1969                                    TPARM_2(change_scroll_region, top, bot));
1970             if (cursor_saved) {
1971                 TPUTS_TRACE("restore_cursor");
1972                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx restore_cursor);
1973             } else {
1974                 SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1975             }
1976
1977             res = scroll_csr_forward(NCURSES_SP_ARGx n, top, bot, top, bot, blank);
1978
1979             TPUTS_TRACE("change_scroll_region");
1980             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
1981                                    TPARM_2(change_scroll_region, 0, maxy));
1982             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1983         }
1984
1985         if (res == ERR && _nc_idlok)
1986             res = scroll_idl(NCURSES_SP_ARGx n, top, bot - n + 1, blank);
1987
1988         /*
1989          * Clear the newly shifted-in text.
1990          */
1991         if (res != ERR
1992             && (non_dest_scroll_region || (memory_below && bot == maxy))) {
1993             static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
1994             if (bot == maxy && clr_eos) {
1995                 GoTo(NCURSES_SP_ARGx bot - n + 1, 0);
1996                 ClrToEOS(NCURSES_SP_ARGx blank2);
1997             } else {
1998                 for (i = 0; i < n; i++) {
1999                     GoTo(NCURSES_SP_ARGx bot - i, 0);
2000                     ClrToEOL(NCURSES_SP_ARGx blank2, FALSE);
2001                 }
2002             }
2003         }
2004
2005     } else {                    /* (n < 0) - scroll down (backward) */
2006         res = scroll_csr_backward(NCURSES_SP_ARGx -n, top, bot, 0, maxy, blank);
2007
2008         if (res == ERR && change_scroll_region) {
2009             if (top != 0
2010                 && (SP_PARM->_cursrow == top ||
2011                     SP_PARM->_cursrow == top - 1)
2012                 && save_cursor && restore_cursor) {
2013                 cursor_saved = TRUE;
2014                 TPUTS_TRACE("save_cursor");
2015                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx save_cursor);
2016             }
2017             TPUTS_TRACE("change_scroll_region");
2018             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
2019                                    TPARM_2(change_scroll_region, top, bot));
2020             if (cursor_saved) {
2021                 TPUTS_TRACE("restore_cursor");
2022                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx restore_cursor);
2023             } else {
2024                 SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2025             }
2026
2027             res = scroll_csr_backward(NCURSES_SP_ARGx
2028                                       -n, top, bot, top, bot, blank);
2029
2030             TPUTS_TRACE("change_scroll_region");
2031             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
2032                                    TPARM_2(change_scroll_region, 0, maxy));
2033             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2034         }
2035
2036         if (res == ERR && _nc_idlok)
2037             res = scroll_idl(NCURSES_SP_ARGx -n, bot + n + 1, top, blank);
2038
2039         /*
2040          * Clear the newly shifted-in text.
2041          */
2042         if (res != ERR
2043             && (non_dest_scroll_region || (memory_above && top == 0))) {
2044             static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
2045             for (i = 0; i < -n; i++) {
2046                 GoTo(NCURSES_SP_ARGx i + top, 0);
2047                 ClrToEOL(NCURSES_SP_ARGx blank2, FALSE);
2048             }
2049         }
2050     }
2051
2052     if (res == ERR)
2053         return (ERR);
2054
2055     _nc_scroll_window(CurScreen(SP_PARM), n, top, bot, blank);
2056
2057     /* shift hash values too - they can be reused */
2058     NCURSES_SP_NAME(_nc_scroll_oldhash) (NCURSES_SP_ARGx n, top, bot);
2059
2060     return (OK);
2061 }
2062
2063 #if NCURSES_SP_FUNCS
2064 NCURSES_EXPORT(int)
2065 _nc_scrolln(int n, int top, int bot, int maxy)
2066 {
2067     return NCURSES_SP_NAME(_nc_scrolln) (CURRENT_SCREEN, n, top, bot, maxy);
2068 }
2069 #endif
2070
2071 NCURSES_EXPORT(void)
2072 NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_DCL0)
2073 {
2074     assert(SP_PARM);
2075
2076     /* make sure terminal is in a sane known state */
2077     SetAttr(SCREEN_ATTRS(SP_PARM), A_NORMAL);
2078     NewScreen(SP_PARM)->_clear = TRUE;
2079
2080     /* reset color pairs and definitions */
2081     if (SP_PARM->_coloron || SP_PARM->_color_defs)
2082         _nc_reset_colors();
2083
2084     /* restore user-defined colors, if any */
2085     if (SP_PARM->_color_defs < 0) {
2086         int n;
2087         SP_PARM->_color_defs = -(SP_PARM->_color_defs);
2088         for (n = 0; n < SP_PARM->_color_defs; ++n) {
2089             if (SP_PARM->_color_table[n].init) {
2090                 NCURSES_SP_NAME(init_color) (NCURSES_SP_ARGx n,
2091                                              SP_PARM->_color_table[n].r,
2092                                              SP_PARM->_color_table[n].g,
2093                                              SP_PARM->_color_table[n].b);
2094             }
2095         }
2096     }
2097
2098     if (exit_attribute_mode)
2099         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_attribute_mode);
2100     else {
2101         /* turn off attributes */
2102         if (exit_alt_charset_mode)
2103             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_alt_charset_mode);
2104         if (exit_standout_mode)
2105             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_standout_mode);
2106         if (exit_underline_mode)
2107             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_underline_mode);
2108     }
2109     if (exit_insert_mode)
2110         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_insert_mode);
2111     if (enter_am_mode && exit_am_mode)
2112         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
2113                                (auto_right_margin
2114                                 ? enter_am_mode
2115                                 : exit_am_mode));
2116 }
2117
2118 #if NCURSES_SP_FUNCS
2119 NCURSES_EXPORT(void)
2120 _nc_screen_resume(void)
2121 {
2122     NCURSES_SP_NAME(_nc_screen_resume) (CURRENT_SCREEN);
2123 }
2124 #endif
2125
2126 NCURSES_EXPORT(void)
2127 NCURSES_SP_NAME(_nc_screen_init) (NCURSES_SP_DCL0)
2128 {
2129     NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_ARG);
2130 }
2131
2132 #if NCURSES_SP_FUNCS
2133 NCURSES_EXPORT(void)
2134 _nc_screen_init(void)
2135 {
2136     NCURSES_SP_NAME(_nc_screen_init) (CURRENT_SCREEN);
2137 }
2138 #endif
2139
2140 /* wrap up screen handling */
2141 NCURSES_EXPORT(void)
2142 NCURSES_SP_NAME(_nc_screen_wrap) (NCURSES_SP_DCL0)
2143 {
2144     if (SP_PARM == 0)
2145         return;
2146
2147     UpdateAttrs(SP_PARM, normal);
2148 #if NCURSES_EXT_FUNCS
2149     if (SP_PARM->_coloron
2150         && !SP_PARM->_default_color) {
2151         static const NCURSES_CH_T blank = NewChar(BLANK_TEXT);
2152         SP_PARM->_default_color = TRUE;
2153         NCURSES_SP_NAME(_nc_do_color) (NCURSES_SP_ARGx
2154                                        -1, 0,
2155                                        FALSE,
2156                                        NCURSES_SP_NAME(_nc_outch));
2157         SP_PARM->_default_color = FALSE;
2158
2159         mvcur(SP_PARM->_cursrow,
2160               SP_PARM->_curscol,
2161               screen_lines(SP_PARM) - 1, 0);
2162
2163         ClrToEOL(NCURSES_SP_ARGx blank, TRUE);
2164     }
2165 #endif
2166     if (SP_PARM->_color_defs) {
2167         _nc_reset_colors();
2168     }
2169 }
2170
2171 #if NCURSES_SP_FUNCS
2172 NCURSES_EXPORT(void)
2173 _nc_screen_wrap(void)
2174 {
2175     NCURSES_SP_NAME(_nc_screen_wrap) (CURRENT_SCREEN);
2176 }
2177 #endif
2178
2179 #if USE_XMC_SUPPORT
2180 NCURSES_EXPORT(void)
2181 NCURSES_SP_NAME(_nc_do_xmc_glitch) (NCURSES_SP_DCLx attr_t previous)
2182 {
2183     if (SP_PARM != 0) {
2184         attr_t chg = XMC_CHANGES(previous ^ AttrOf(SCREEN_ATTRS(SP_PARM)));
2185
2186         while (chg != 0) {
2187             if (chg & 1) {
2188                 SP_PARM->_curscol += magic_cookie_glitch;
2189                 if (SP_PARM->_curscol >= SP_PARM->_columns)
2190                     wrap_cursor(NCURSES_SP_ARG);
2191                 TR(TRACE_UPDATE, ("bumped to %d,%d after cookie",
2192                                   SP_PARM->_cursrow, SP_PARM->_curscol));
2193             }
2194             chg >>= 1;
2195         }
2196     }
2197 }
2198
2199 #if NCURSES_SP_FUNCS
2200 NCURSES_EXPORT(void)
2201 _nc_do_xmc_glitch(attr_t previous)
2202 {
2203     NCURSES_SP_NAME(_nc_do_xmc_glitch) (CURRENT_SCREEN, previous);
2204 }
2205 #endif
2206
2207 #endif /* USE_XMC_SUPPORT */