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