]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/tty/tty_update.c
7e99b358eb4e93d796d68fda3d678029b1b7791e
[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.255 2009/05/10 00:53:14 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 (CurScreen(SP_PARM) == 0
672         || NewScreen(SP_PARM) == 0)
673         returnCode(ERR);
674
675 #ifdef TRACE
676     if (USE_TRACEF(TRACE_UPDATE)) {
677         if (CurScreen(SP_PARM)->_clear)
678             _tracef("curscr is clear");
679         else
680             _tracedump("curscr", CurScreen(SP_PARM));
681         _tracedump("newscr", NewScreen(SP_PARM));
682         _nc_unlock_global(tracef);
683     }
684 #endif /* TRACE */
685
686     _nc_signal_handler(FALSE);
687
688     if (SP_PARM->_fifohold)
689         SP_PARM->_fifohold--;
690
691 #if USE_SIZECHANGE
692     if (SP_PARM->_endwin || _nc_handle_sigwinch(SP_PARM)) {
693         /*
694          * This is a transparent extension:  XSI does not address it,
695          * and applications need not know that ncurses can do it.
696          *
697          * Check if the terminal size has changed while curses was off
698          * (this can happen in an xterm, for example), and resize the
699          * ncurses data structures accordingly.
700          */
701         _nc_update_screensize(SP_PARM);
702     }
703 #endif
704
705     if (SP_PARM->_endwin) {
706
707         T(("coming back from shell mode"));
708         NCURSES_SP_NAME(reset_prog_mode) (NCURSES_SP_ARG);
709
710         NCURSES_SP_NAME(_nc_mvcur_resume) (NCURSES_SP_ARG);
711         NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_ARG);
712         SP_PARM->_mouse_resume(SP_PARM);
713
714         SP_PARM->_endwin = FALSE;
715     }
716 #if USE_TRACE_TIMES
717     /* zero the metering machinery */
718     RESET_OUTCHARS();
719     (void) times(&before);
720 #endif /* USE_TRACE_TIMES */
721
722     /*
723      * This is the support for magic-cookie terminals.  The theory:  we scan
724      * the virtual screen looking for attribute turnons.  Where we find one,
725      * check to make sure it's realizable by seeing if the required number of
726      * un-attributed blanks are present before and after the attributed range;
727      * try to shift the range boundaries over blanks (not changing the screen
728      * display) so this becomes true.  If it is, shift the beginning attribute
729      * change appropriately (the end one, if we've gotten this far, is
730      * guaranteed room for its cookie).  If not, nuke the added attributes out
731      * of the span.
732      */
733 #if USE_XMC_SUPPORT
734     if (magic_cookie_glitch > 0) {
735         int j, k;
736         attr_t rattr = A_NORMAL;
737
738         for (i = 0; i < screen_lines(SP_PARM); i++) {
739             for (j = 0; j < screen_columns(SP_PARM); j++) {
740                 bool failed = FALSE;
741                 NCURSES_CH_T *thisline = NewScreen(SP_PARM)->_line[i].text;
742                 attr_t thisattr = AttrOf(thisline[j]) & SP_PARM->_xmc_triggers;
743                 attr_t turnon = thisattr & ~rattr;
744
745                 /* is an attribute turned on here? */
746                 if (turnon == 0) {
747                     rattr = thisattr;
748                     continue;
749                 }
750
751                 TR(TRACE_ATTRS, ("At (%d, %d): from %s...", i, j, _traceattr(rattr)));
752                 TR(TRACE_ATTRS, ("...to %s", _traceattr(turnon)));
753
754                 /*
755                  * If the attribute change location is a blank with a "safe"
756                  * attribute, undo the attribute turnon.  This may ensure
757                  * there's enough room to set the attribute before the first
758                  * non-blank in the run.
759                  */
760 #define SAFE(scr,a)     (!((a) & (scr)->_xmc_triggers))
761                 if (ISBLANK(thisline[j]) && SAFE(SP_PARM, turnon)) {
762                     RemAttr(thisline[j], turnon);
763                     continue;
764                 }
765
766                 /* check that there's enough room at start of span */
767                 for (k = 1; k <= magic_cookie_glitch; k++) {
768                     if (j - k < 0
769                         || !ISBLANK(thisline[j - k])
770                         || !SAFE(SP_PARM, AttrOf(thisline[j - k]))) {
771                         failed = TRUE;
772                         TR(TRACE_ATTRS, ("No room at start in %d,%d%s%s",
773                                          i, j - k,
774                                          (ISBLANK(thisline[j - k])
775                                           ? ""
776                                           : ":nonblank"),
777                                          (SAFE(SP_PARM, AttrOf(thisline[j - k]))
778                                           ? ""
779                                           : ":unsafe")));
780                         break;
781                     }
782                 }
783                 if (!failed) {
784                     bool end_onscreen = FALSE;
785                     int m, n = j;
786
787                     /* find end of span, if it's onscreen */
788                     for (m = i; m < screen_lines(SP_PARM); m++) {
789                         for (; n < screen_columns(SP_PARM); n++) {
790                             attr_t testattr
791                             = AttrOf(NewScreen(SP_PARM)->_line[m].text[n]);
792
793                             if ((testattr & SP_PARM->_xmc_triggers) == rattr) {
794                                 end_onscreen = TRUE;
795                                 TR(TRACE_ATTRS,
796                                    ("Range attributed with %s ends at (%d, %d)",
797                                     _traceattr(turnon), m, n));
798                                 goto foundit;
799                             }
800                         }
801                         n = 0;
802                     }
803                     TR(TRACE_ATTRS,
804                        ("Range attributed with %s ends offscreen",
805                         _traceattr(turnon)));
806                   foundit:;
807
808                     if (end_onscreen) {
809                         NCURSES_CH_T *lastline =
810                         NewScreen(SP_PARM)->_line[m].text;
811
812                         /*
813                          * If there are safely-attributed blanks at the end of
814                          * the range, shorten the range.  This will help ensure
815                          * that there is enough room at end of span.
816                          */
817                         while (n >= 0
818                                && ISBLANK(lastline[n])
819                                && SAFE(SP_PARM, AttrOf(lastline[n]))) {
820                             RemAttr(lastline[n--], turnon);
821                         }
822
823                         /* check that there's enough room at end of span */
824                         for (k = 1; k <= magic_cookie_glitch; k++) {
825                             if (n + k >= screen_columns(SP_PARM)
826                                 || !ISBLANK(lastline[n + k])
827                                 || !SAFE(SP_PARM, AttrOf(lastline[n + k]))) {
828                                 failed = TRUE;
829                                 TR(TRACE_ATTRS,
830                                    ("No room at end in %d,%d%s%s",
831                                     i, j - k,
832                                     (ISBLANK(lastline[n + k])
833                                      ? ""
834                                      : ":nonblank"),
835                                     (SAFE(SP_PARM, AttrOf(lastline[n + k]))
836                                      ? ""
837                                      : ":unsafe")));
838                                 break;
839                             }
840                         }
841                     }
842                 }
843
844                 if (failed) {
845                     int p, q = j;
846
847                     TR(TRACE_ATTRS,
848                        ("Clearing %s beginning at (%d, %d)",
849                         _traceattr(turnon), i, j));
850
851                     /* turn off new attributes over span */
852                     for (p = i; p < screen_lines(SP_PARM); p++) {
853                         for (; q < screen_columns(SP_PARM); q++) {
854                             attr_t testattr =
855                             AttrOf(NewScreen(SP_PARM)->_line[p].text[q]);
856                             if ((testattr & SP_PARM->_xmc_triggers) == rattr)
857                                 goto foundend;
858                             RemAttr(NewScreen(SP_PARM)->_line[p].text[q], turnon);
859                         }
860                         q = 0;
861                     }
862                   foundend:;
863                 } else {
864                     TR(TRACE_ATTRS,
865                        ("Cookie space for %s found before (%d, %d)",
866                         _traceattr(turnon), i, j));
867
868                     /*
869                      * Back up the start of range so there's room for cookies
870                      * before the first nonblank character.
871                      */
872                     for (k = 1; k <= magic_cookie_glitch; k++)
873                         AddAttr(thisline[j - k], turnon);
874                 }
875
876                 rattr = thisattr;
877             }
878         }
879
880 #ifdef TRACE
881         /* show altered highlights after magic-cookie check */
882         if (USE_TRACEF(TRACE_UPDATE)) {
883             _tracef("After magic-cookie check...");
884             _tracedump("newscr", NewScreen(SP_PARM));
885             _nc_unlock_global(tracef);
886         }
887 #endif /* TRACE */
888     }
889 #endif /* USE_XMC_SUPPORT */
890
891     nonempty = 0;
892     if (CurScreen(SP_PARM)->_clear || NewScreen(SP_PARM)->_clear) {     /* force refresh ? */
893         ClrUpdate(NCURSES_SP_ARG);
894         CurScreen(SP_PARM)->_clear = FALSE;     /* reset flag */
895         NewScreen(SP_PARM)->_clear = FALSE;     /* reset flag */
896     } else {
897         int changedlines = CHECK_INTERVAL;
898
899         if (check_pending(NCURSES_SP_ARG))
900             goto cleanup;
901
902         nonempty = min(screen_lines(SP_PARM), NewScreen(SP_PARM)->_maxy + 1);
903
904         if (SP_PARM->_scrolling) {
905             _nc_scroll_optimize();
906         }
907
908         nonempty = ClrBottom(NCURSES_SP_ARGx nonempty);
909
910         TR(TRACE_UPDATE, ("Transforming lines, nonempty %d", nonempty));
911         for (i = 0; i < nonempty; i++) {
912             /*
913              * Here is our line-breakout optimization.
914              */
915             if (changedlines == CHECK_INTERVAL) {
916                 if (check_pending(NCURSES_SP_ARG))
917                     goto cleanup;
918                 changedlines = 0;
919             }
920
921             /*
922              * newscr.line[i].firstchar is normally set
923              * by wnoutrefresh.  curscr.line[i].firstchar
924              * is normally set by _nc_scroll_window in the
925              * vertical-movement optimization code,
926              */
927             if (NewScreen(SP_PARM)->_line[i].firstchar != _NOCHANGE
928                 || CurScreen(SP_PARM)->_line[i].firstchar != _NOCHANGE) {
929                 TransformLine(NCURSES_SP_ARGx i);
930                 changedlines++;
931             }
932
933             /* mark line changed successfully */
934             if (i <= NewScreen(SP_PARM)->_maxy) {
935                 MARK_NOCHANGE(NewScreen(SP_PARM), i);
936             }
937             if (i <= CurScreen(SP_PARM)->_maxy) {
938                 MARK_NOCHANGE(CurScreen(SP_PARM), i);
939             }
940         }
941     }
942
943     /* put everything back in sync */
944     for (i = nonempty; i <= NewScreen(SP_PARM)->_maxy; i++) {
945         MARK_NOCHANGE(NewScreen(SP_PARM), i);
946     }
947     for (i = nonempty; i <= CurScreen(SP_PARM)->_maxy; i++) {
948         MARK_NOCHANGE(CurScreen(SP_PARM), i);
949     }
950
951     if (!NewScreen(SP_PARM)->_leaveok) {
952         CurScreen(SP_PARM)->_curx = NewScreen(SP_PARM)->_curx;
953         CurScreen(SP_PARM)->_cury = NewScreen(SP_PARM)->_cury;
954
955         GoTo(NCURSES_SP_ARGx CurScreen(SP_PARM)->_cury, CurScreen(SP_PARM)->_curx);
956     }
957
958   cleanup:
959     /*
960      * We would like to keep the physical screen in normal mode in case we get
961      * other processes writing to the screen.  This goal cannot be met for
962      * magic cookies since it interferes with attributes that may propagate
963      * past the current position.
964      */
965 #if USE_XMC_SUPPORT
966     if (magic_cookie_glitch != 0)
967 #endif
968         UpdateAttrs(SP_PARM, normal);
969
970     NCURSES_SP_NAME(_nc_flush) (NCURSES_SP_ARG);
971     WINDOW_ATTRS(CurScreen(SP_PARM)) = WINDOW_ATTRS(NewScreen(SP_PARM));
972
973 #if USE_TRACE_TIMES
974     (void) times(&after);
975     TR(TRACE_TIMES,
976        ("Update cost: %ld chars, %ld clocks system time, %ld clocks user time",
977         _nc_outchars,
978         (long) (after.tms_stime - before.tms_stime),
979         (long) (after.tms_utime - before.tms_utime)));
980 #endif /* USE_TRACE_TIMES */
981
982     _nc_signal_handler(TRUE);
983
984     returnCode(OK);
985 }
986
987 #if NCURSES_SP_FUNCS
988 NCURSES_EXPORT(int)
989 doupdate(void)
990 {
991     return NCURSES_SP_NAME(doupdate) (CURRENT_SCREEN);
992 }
993 #endif
994
995 /*
996  *      ClrBlank(win)
997  *
998  *      Returns the attributed character that corresponds to the "cleared"
999  *      screen.  If the terminal has the back-color-erase feature, this will be
1000  *      colored according to the wbkgd() call.
1001  *
1002  *      We treat 'curscr' specially because it isn't supposed to be set directly
1003  *      in the wbkgd() call.  Assume 'stdscr' for this case.
1004  */
1005 #define BCE_ATTRS (A_NORMAL|A_COLOR)
1006 #define BCE_BKGD(win) (((win) == CurScreen(SP_PARM) ? StdScreen(SP_PARM) : (win))->_nc_bkgd)
1007
1008 static NCURSES_INLINE NCURSES_CH_T
1009 ClrBlank(NCURSES_SP_DCLx WINDOW *win)
1010 {
1011     NCURSES_CH_T blank = blankchar;
1012     if (back_color_erase)
1013         AddAttr(blank, (AttrOf(BCE_BKGD(win)) & BCE_ATTRS));
1014     return blank;
1015 }
1016
1017 /*
1018 **      ClrUpdate()
1019 **
1020 **      Update by clearing and redrawing the entire screen.
1021 **
1022 */
1023
1024 static void
1025 ClrUpdate(NCURSES_SP_DCL0)
1026 {
1027     TR(TRACE_UPDATE, (T_CALLED("ClrUpdate")));
1028     if (0 != SP_PARM) {
1029         int i;
1030         NCURSES_CH_T blank = ClrBlank(NCURSES_SP_ARGx StdScreen(SP_PARM));
1031         int nonempty = min(screen_lines(SP_PARM),
1032                            NewScreen(SP_PARM)->_maxy + 1);
1033
1034         ClearScreen(NCURSES_SP_ARGx blank);
1035
1036         TR(TRACE_UPDATE, ("updating screen from scratch"));
1037
1038         nonempty = ClrBottom(NCURSES_SP_ARGx nonempty);
1039
1040         for (i = 0; i < nonempty; i++)
1041             TransformLine(NCURSES_SP_ARGx i);
1042     }
1043     TR(TRACE_UPDATE, (T_RETURN("")));
1044 }
1045
1046 /*
1047 **      ClrToEOL(blank)
1048 **
1049 **      Clear to end of current line, starting at the cursor position
1050 */
1051
1052 static void
1053 ClrToEOL(NCURSES_SP_DCLx NCURSES_CH_T blank, bool needclear)
1054 {
1055     int j;
1056
1057     if (CurScreen(SP_PARM) != 0
1058         && SP_PARM->_cursrow >= 0) {
1059         for (j = SP_PARM->_curscol; j < screen_columns(SP_PARM); j++) {
1060             if (j >= 0) {
1061                 NCURSES_CH_T *cp =
1062                 &(CurScreen(SP_PARM)->_line[SP_PARM->_cursrow].text[j]);
1063
1064                 if (!CharEq(*cp, blank)) {
1065                     *cp = blank;
1066                     needclear = TRUE;
1067                 }
1068             }
1069         }
1070     } else {
1071         needclear = TRUE;
1072     }
1073
1074     if (needclear) {
1075         UpdateAttrs(SP_PARM, blank);
1076         TPUTS_TRACE("clr_eol");
1077         if (clr_eol && SP_PARM->_el_cost <= (screen_columns(SP_PARM) - SP_PARM->_curscol)) {
1078             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clr_eol);
1079         } else {
1080             int count = (screen_columns(SP_PARM) - SP_PARM->_curscol);
1081             while (count-- > 0)
1082                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1083         }
1084     }
1085 }
1086
1087 /*
1088 **      ClrToEOS(blank)
1089 **
1090 **      Clear to end of screen, starting at the cursor position
1091 */
1092
1093 static void
1094 ClrToEOS(NCURSES_SP_DCLx NCURSES_CH_T blank)
1095 {
1096     int row, col;
1097
1098     if (0 == SP_PARM)
1099         return;
1100
1101     row = SP_PARM->_cursrow;
1102     col = SP_PARM->_curscol;
1103
1104     UpdateAttrs(SP_PARM, blank);
1105     TPUTS_TRACE("clr_eos");
1106     NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1107                             clr_eos,
1108                             screen_lines(SP_PARM) - row,
1109                             NCURSES_SP_NAME(_nc_outch));
1110
1111     while (col < screen_columns(SP_PARM))
1112         CurScreen(SP_PARM)->_line[row].text[col++] = blank;
1113
1114     for (row++; row < screen_lines(SP_PARM); row++) {
1115         for (col = 0; col < screen_columns(SP_PARM); col++)
1116             CurScreen(SP_PARM)->_line[row].text[col] = blank;
1117     }
1118 }
1119
1120 /*
1121  *      ClrBottom(total)
1122  *
1123  *      Test if clearing the end of the screen would satisfy part of the
1124  *      screen-update.  Do this by scanning backwards through the lines in the
1125  *      screen, checking if each is blank, and one or more are changed.
1126  */
1127 static int
1128 ClrBottom(NCURSES_SP_DCLx int total)
1129 {
1130     int row;
1131     int col;
1132     int top = total;
1133     int last = min(screen_columns(SP_PARM), NewScreen(SP_PARM)->_maxx + 1);
1134     NCURSES_CH_T blank = NewScreen(SP_PARM)->_line[total - 1].text[last - 1];
1135     bool ok;
1136
1137     if (clr_eos && can_clear_with(NCURSES_SP_ARGx CHREF(blank))) {
1138
1139         for (row = total - 1; row >= 0; row--) {
1140             for (col = 0, ok = TRUE; ok && col < last; col++) {
1141                 ok = (CharEq(NewScreen(SP_PARM)->_line[row].text[col], blank));
1142             }
1143             if (!ok)
1144                 break;
1145
1146             for (col = 0; ok && col < last; col++) {
1147                 ok = (CharEq(CurScreen(SP_PARM)->_line[row].text[col], blank));
1148             }
1149             if (!ok)
1150                 top = row;
1151         }
1152
1153         /* don't use clr_eos for just one line if clr_eol available */
1154         if (top < total) {
1155             GoTo(NCURSES_SP_ARGx top, 0);
1156             ClrToEOS(NCURSES_SP_ARGx blank);
1157             if (SP_PARM->oldhash && SP_PARM->newhash) {
1158                 for (row = top; row < screen_lines(SP_PARM); row++)
1159                     SP_PARM->oldhash[row] = SP_PARM->newhash[row];
1160             }
1161         }
1162     }
1163     return top;
1164 }
1165
1166 #if USE_XMC_SUPPORT
1167 #if USE_WIDEC_SUPPORT
1168 #define check_xmc_transition(sp, a, b)                                  \
1169     ((((a)->attr ^ (b)->attr) & ~((a)->attr) & (sp)->_xmc_triggers) != 0)
1170 #define xmc_turn_on(sp,a,b) check_xmc_transition(sp,&(a), &(b))
1171 #else
1172 #define xmc_turn_on(sp,a,b) ((((a)^(b)) & ~(a) & (sp)->_xmc_triggers) != 0)
1173 #endif
1174
1175 #define xmc_new(sp,r,c) NewScreen(SP_PARM)->_line[r].text[c]
1176 #define xmc_turn_off(sp,a,b) xmc_turn_on(sp,b,a)
1177 #endif /* USE_XMC_SUPPORT */
1178
1179 /*
1180 **      TransformLine(lineno)
1181 **
1182 **      Transform the given line in curscr to the one in newscr, using
1183 **      Insert/Delete Character if _nc_idcok && has_ic().
1184 **
1185 **              firstChar = position of first different character in line
1186 **              oLastChar = position of last different character in old line
1187 **              nLastChar = position of last different character in new line
1188 **
1189 **              move to firstChar
1190 **              overwrite chars up to min(oLastChar, nLastChar)
1191 **              if oLastChar < nLastChar
1192 **                      insert newLine[oLastChar+1..nLastChar]
1193 **              else
1194 **                      delete oLastChar - nLastChar spaces
1195 */
1196
1197 static void
1198 TransformLine(NCURSES_SP_DCLx int const lineno)
1199 {
1200     int firstChar, oLastChar, nLastChar;
1201     NCURSES_CH_T *newLine = NewScreen(SP_PARM)->_line[lineno].text;
1202     NCURSES_CH_T *oldLine = CurScreen(SP_PARM)->_line[lineno].text;
1203     int n;
1204     bool attrchanged = FALSE;
1205
1206     TR(TRACE_UPDATE, (T_CALLED("TransformLine(%p, %d)"), SP_PARM, lineno));
1207
1208     /* copy new hash value to old one */
1209     if (SP_PARM->oldhash && SP_PARM->newhash)
1210         SP_PARM->oldhash[lineno] = SP_PARM->newhash[lineno];
1211
1212     /*
1213      * If we have colors, there is the possibility of having two color pairs
1214      * that display as the same colors.  For instance, Lynx does this.  Check
1215      * for this case, and update the old line with the new line's colors when
1216      * they are equivalent.
1217      */
1218     if (SP_PARM->_coloron) {
1219         int oldPair;
1220         int newPair;
1221
1222         for (n = 0; n < screen_columns(SP_PARM); n++) {
1223             if (!CharEq(newLine[n], oldLine[n])) {
1224                 oldPair = GetPair(oldLine[n]);
1225                 newPair = GetPair(newLine[n]);
1226                 if (oldPair != newPair
1227                     && unColor(oldLine[n]) == unColor(newLine[n])) {
1228                     if (oldPair < SP_PARM->_pair_limit
1229                         && newPair < SP_PARM->_pair_limit
1230                         && (SP_PARM->_color_pairs[oldPair] ==
1231                             SP_PARM->_color_pairs[newPair])) {
1232                         SetPair(oldLine[n], GetPair(newLine[n]));
1233                     }
1234                 }
1235             }
1236         }
1237     }
1238
1239     if (ceol_standout_glitch && clr_eol) {
1240         firstChar = 0;
1241         while (firstChar < screen_columns(SP_PARM)) {
1242             if (!SameAttrOf(newLine[firstChar], oldLine[firstChar])) {
1243                 attrchanged = TRUE;
1244                 break;
1245             }
1246             firstChar++;
1247         }
1248     }
1249
1250     firstChar = 0;
1251
1252     if (attrchanged) {          /* we may have to disregard the whole line */
1253         GoTo(NCURSES_SP_ARGx lineno, firstChar);
1254         ClrToEOL(NCURSES_SP_ARGx
1255                  ClrBlank(NCURSES_SP_ARGx CurScreen(SP_PARM)),
1256                  FALSE);
1257         PutRange(NCURSES_SP_ARGx
1258                  oldLine, newLine, lineno, 0,
1259                  screen_columns(SP_PARM) - 1);
1260 #if USE_XMC_SUPPORT
1261
1262         /*
1263          * This is a very simple loop to paint characters which may have the
1264          * magic cookie glitch embedded.  It doesn't know much about video
1265          * attributes which are continued from one line to the next.  It
1266          * assumes that we have filtered out requests for attribute changes
1267          * that do not get mapped to blank positions.
1268          *
1269          * FIXME: we are not keeping track of where we put the cookies, so this
1270          * will work properly only once, since we may overwrite a cookie in a
1271          * following operation.
1272          */
1273     } else if (magic_cookie_glitch > 0) {
1274         GoTo(NCURSES_SP_ARGx lineno, firstChar);
1275         for (n = 0; n < screen_columns(SP_PARM); n++) {
1276             int m = n + magic_cookie_glitch;
1277
1278             /* check for turn-on:
1279              * If we are writing an attributed blank, where the
1280              * previous cell is not attributed.
1281              */
1282             if (ISBLANK(newLine[n])
1283                 && ((n > 0
1284                      && xmc_turn_on(SP_PARM, newLine[n - 1], newLine[n]))
1285                     || (n == 0
1286                         && lineno > 0
1287                         && xmc_turn_on(SP_PARM,
1288                                        xmc_new(SP_PARM, lineno - 1,
1289                                                screen_columns(SP_PARM) - 1),
1290                                        newLine[n])))) {
1291                 n = m;
1292             }
1293
1294             PutChar(NCURSES_SP_ARGx CHREF(newLine[n]));
1295
1296             /* check for turn-off:
1297              * If we are writing an attributed non-blank, where the
1298              * next cell is blank, and not attributed.
1299              */
1300             if (!ISBLANK(newLine[n])
1301                 && ((n + 1 < screen_columns(SP_PARM)
1302                      && xmc_turn_off(SP_PARM, newLine[n], newLine[n + 1]))
1303                     || (n + 1 >= screen_columns(SP_PARM)
1304                         && lineno + 1 < screen_lines(SP_PARM)
1305                         && xmc_turn_off(SP_PARM,
1306                                         newLine[n],
1307                                         xmc_new(SP_PARM, lineno + 1, 0))))) {
1308                 n = m;
1309             }
1310
1311         }
1312 #endif
1313     } else {
1314         NCURSES_CH_T blank;
1315
1316         /* it may be cheap to clear leading whitespace with clr_bol */
1317         blank = newLine[0];
1318         if (clr_bol && can_clear_with(NCURSES_SP_ARGx CHREF(blank))) {
1319             int oFirstChar, nFirstChar;
1320
1321             for (oFirstChar = 0;
1322                  oFirstChar < screen_columns(SP_PARM);
1323                  oFirstChar++)
1324                 if (!CharEq(oldLine[oFirstChar], blank))
1325                     break;
1326             for (nFirstChar = 0;
1327                  nFirstChar < screen_columns(SP_PARM);
1328                  nFirstChar++)
1329                 if (!CharEq(newLine[nFirstChar], blank))
1330                     break;
1331
1332             if (nFirstChar == oFirstChar) {
1333                 firstChar = nFirstChar;
1334                 /* find the first differing character */
1335                 while (firstChar < screen_columns(SP_PARM)
1336                        && CharEq(newLine[firstChar], oldLine[firstChar]))
1337                     firstChar++;
1338             } else if (oFirstChar > nFirstChar) {
1339                 firstChar = nFirstChar;
1340             } else {            /* oFirstChar < nFirstChar */
1341                 firstChar = oFirstChar;
1342                 if (SP_PARM->_el1_cost < nFirstChar - oFirstChar) {
1343                     if (nFirstChar >= screen_columns(SP_PARM)
1344                         && SP_PARM->_el_cost <= SP_PARM->_el1_cost) {
1345                         GoTo(NCURSES_SP_ARGx lineno, 0);
1346                         UpdateAttrs(SP_PARM, blank);
1347                         TPUTS_TRACE("clr_eol");
1348                         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clr_eol);
1349                     } else {
1350                         GoTo(NCURSES_SP_ARGx lineno, nFirstChar - 1);
1351                         UpdateAttrs(SP_PARM, blank);
1352                         TPUTS_TRACE("clr_bol");
1353                         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clr_bol);
1354                     }
1355
1356                     while (firstChar < nFirstChar)
1357                         oldLine[firstChar++] = blank;
1358                 }
1359             }
1360         } else {
1361             /* find the first differing character */
1362             while (firstChar < screen_columns(SP_PARM)
1363                    && CharEq(newLine[firstChar], oldLine[firstChar]))
1364                 firstChar++;
1365         }
1366         /* if there wasn't one, we're done */
1367         if (firstChar >= screen_columns(SP_PARM)) {
1368             TR(TRACE_UPDATE, (T_RETURN("")));
1369             return;
1370         }
1371
1372         blank = newLine[screen_columns(SP_PARM) - 1];
1373
1374         if (!can_clear_with(NCURSES_SP_ARGx CHREF(blank))) {
1375             /* find the last differing character */
1376             nLastChar = screen_columns(SP_PARM) - 1;
1377
1378             while (nLastChar > firstChar
1379                    && CharEq(newLine[nLastChar], oldLine[nLastChar]))
1380                 nLastChar--;
1381
1382             if (nLastChar >= firstChar) {
1383                 GoTo(NCURSES_SP_ARGx lineno, firstChar);
1384                 PutRange(NCURSES_SP_ARGx
1385                          oldLine,
1386                          newLine,
1387                          lineno,
1388                          firstChar,
1389                          nLastChar);
1390                 memcpy(oldLine + firstChar,
1391                        newLine + firstChar,
1392                        (nLastChar - firstChar + 1) * sizeof(NCURSES_CH_T));
1393             }
1394             TR(TRACE_UPDATE, (T_RETURN("")));
1395             return;
1396         }
1397
1398         /* find last non-blank character on old line */
1399         oLastChar = screen_columns(SP_PARM) - 1;
1400         while (oLastChar > firstChar && CharEq(oldLine[oLastChar], blank))
1401             oLastChar--;
1402
1403         /* find last non-blank character on new line */
1404         nLastChar = screen_columns(SP_PARM) - 1;
1405         while (nLastChar > firstChar && CharEq(newLine[nLastChar], blank))
1406             nLastChar--;
1407
1408         if ((nLastChar == firstChar)
1409             && (SP_PARM->_el_cost < (oLastChar - nLastChar))) {
1410             GoTo(NCURSES_SP_ARGx lineno, firstChar);
1411             if (!CharEq(newLine[firstChar], blank))
1412                 PutChar(NCURSES_SP_ARGx CHREF(newLine[firstChar]));
1413             ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1414         } else if ((nLastChar != oLastChar)
1415                    && (!CharEq(newLine[nLastChar], oldLine[oLastChar])
1416                        || !(_nc_idcok && has_ic()))) {
1417             GoTo(NCURSES_SP_ARGx lineno, firstChar);
1418             if ((oLastChar - nLastChar) > SP_PARM->_el_cost) {
1419                 if (PutRange(NCURSES_SP_ARGx
1420                              oldLine,
1421                              newLine,
1422                              lineno,
1423                              firstChar,
1424                              nLastChar)) {
1425                     GoTo(NCURSES_SP_ARGx lineno, nLastChar + 1);
1426                 }
1427                 ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1428             } else {
1429                 n = max(nLastChar, oLastChar);
1430                 PutRange(NCURSES_SP_ARGx
1431                          oldLine,
1432                          newLine,
1433                          lineno,
1434                          firstChar,
1435                          n);
1436             }
1437         } else {
1438             int nLastNonblank = nLastChar;
1439             int oLastNonblank = oLastChar;
1440
1441             /* find the last characters that really differ */
1442             /* can be -1 if no characters differ */
1443             while (CharEq(newLine[nLastChar], oldLine[oLastChar])) {
1444                 /* don't split a wide char */
1445                 if (isWidecExt(newLine[nLastChar]) &&
1446                     !CharEq(newLine[nLastChar - 1], oldLine[oLastChar - 1]))
1447                     break;
1448                 nLastChar--;
1449                 oLastChar--;
1450                 if (nLastChar == -1 || oLastChar == -1)
1451                     break;
1452             }
1453
1454             n = min(oLastChar, nLastChar);
1455             if (n >= firstChar) {
1456                 GoTo(NCURSES_SP_ARGx lineno, firstChar);
1457                 PutRange(NCURSES_SP_ARGx
1458                          oldLine,
1459                          newLine,
1460                          lineno,
1461                          firstChar,
1462                          n);
1463             }
1464
1465             if (oLastChar < nLastChar) {
1466                 int m = max(nLastNonblank, oLastNonblank);
1467 #if USE_WIDEC_SUPPORT
1468                 while (isWidecExt(newLine[n + 1]) && n) {
1469                     --n;
1470                     --oLastChar;
1471                 }
1472 #endif
1473                 GoTo(NCURSES_SP_ARGx lineno, n + 1);
1474                 if ((nLastChar < nLastNonblank)
1475                     || InsCharCost(SP_PARM, nLastChar - oLastChar) > (m - n)) {
1476                     PutRange(NCURSES_SP_ARGx
1477                              oldLine,
1478                              newLine,
1479                              lineno,
1480                              n + 1,
1481                              m);
1482                 } else {
1483                     InsStr(NCURSES_SP_ARGx &newLine[n + 1], nLastChar - oLastChar);
1484                 }
1485             } else if (oLastChar > nLastChar) {
1486                 GoTo(NCURSES_SP_ARGx lineno, n + 1);
1487                 if (DelCharCost(SP_PARM, oLastChar - nLastChar)
1488                     > SP_PARM->_el_cost + nLastNonblank - (n + 1)) {
1489                     if (PutRange(NCURSES_SP_ARGx oldLine, newLine, lineno,
1490                                  n + 1, nLastNonblank))
1491                           GoTo(NCURSES_SP_ARGx lineno, nLastNonblank + 1);
1492                     ClrToEOL(NCURSES_SP_ARGx blank, FALSE);
1493                 } else {
1494                     /*
1495                      * The delete-char sequence will
1496                      * effectively shift in blanks from the
1497                      * right margin of the screen.  Ensure
1498                      * that they are the right color by
1499                      * setting the video attributes from
1500                      * the last character on the row.
1501                      */
1502                     UpdateAttrs(SP_PARM, blank);
1503                     DelChar(NCURSES_SP_ARGx oLastChar - nLastChar);
1504                 }
1505             }
1506         }
1507     }
1508
1509     /* update the code's internal representation */
1510     if (screen_columns(SP_PARM) > firstChar)
1511         memcpy(oldLine + firstChar,
1512                newLine + firstChar,
1513                (screen_columns(SP_PARM) - firstChar) * sizeof(NCURSES_CH_T));
1514     TR(TRACE_UPDATE, (T_RETURN("")));
1515     return;
1516 }
1517
1518 /*
1519 **      ClearScreen(blank)
1520 **
1521 **      Clear the physical screen and put cursor at home
1522 **
1523 */
1524
1525 static void
1526 ClearScreen(NCURSES_SP_DCLx NCURSES_CH_T blank)
1527 {
1528     int i, j;
1529     bool fast_clear = (clear_screen || clr_eos || clr_eol);
1530
1531     TR(TRACE_UPDATE, ("ClearScreen() called"));
1532
1533 #if NCURSES_EXT_FUNCS
1534     if (SP_PARM->_coloron
1535         && !SP_PARM->_default_color) {
1536         NCURSES_SP_NAME(_nc_do_color) (NCURSES_SP_ARGx
1537                                        GET_SCREEN_PAIR(SP_PARM),
1538                                        0,
1539                                        FALSE,
1540                                        NCURSES_SP_NAME(_nc_outch));
1541         if (!back_color_erase) {
1542             fast_clear = FALSE;
1543         }
1544     }
1545 #endif
1546
1547     if (fast_clear) {
1548         if (clear_screen) {
1549             UpdateAttrs(SP_PARM, blank);
1550             TPUTS_TRACE("clear_screen");
1551             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clear_screen);
1552             SP_PARM->_cursrow = SP_PARM->_curscol = 0;
1553             position_check(SP_PARM,
1554                            SP_PARM->_cursrow,
1555                            SP_PARM->_curscol,
1556                            "ClearScreen");
1557         } else if (clr_eos) {
1558             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1559             GoTo(NCURSES_SP_ARGx 0, 0);
1560
1561             UpdateAttrs(SP_PARM, blank);
1562             TPUTS_TRACE("clr_eos");
1563             NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1564                                     clr_eos,
1565                                     screen_lines(SP_PARM),
1566                                     NCURSES_SP_NAME(_nc_outch));
1567         } else if (clr_eol) {
1568             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1569
1570             UpdateAttrs(SP_PARM, blank);
1571             for (i = 0; i < screen_lines(SP_PARM); i++) {
1572                 GoTo(NCURSES_SP_ARGx i, 0);
1573                 TPUTS_TRACE("clr_eol");
1574                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx clr_eol);
1575             }
1576             GoTo(NCURSES_SP_ARGx 0, 0);
1577         }
1578     } else {
1579         UpdateAttrs(SP_PARM, blank);
1580         for (i = 0; i < screen_lines(SP_PARM); i++) {
1581             GoTo(NCURSES_SP_ARGx i, 0);
1582             for (j = 0; j < screen_columns(SP_PARM); j++)
1583                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1584         }
1585         GoTo(NCURSES_SP_ARGx 0, 0);
1586     }
1587
1588     for (i = 0; i < screen_lines(SP_PARM); i++) {
1589         for (j = 0; j < screen_columns(SP_PARM); j++)
1590             CurScreen(SP_PARM)->_line[i].text[j] = blank;
1591     }
1592
1593     TR(TRACE_UPDATE, ("screen cleared"));
1594 }
1595
1596 /*
1597 **      InsStr(line, count)
1598 **
1599 **      Insert the count characters pointed to by line.
1600 **
1601 */
1602
1603 static void
1604 InsStr(NCURSES_SP_DCLx NCURSES_CH_T * line, int count)
1605 {
1606     TR(TRACE_UPDATE, ("InsStr(%p, %p,%d) called", SP_PARM, line, count));
1607
1608     /* Prefer parm_ich as it has the smallest cost - no need to shift
1609      * the whole line on each character. */
1610     /* The order must match that of InsCharCost. */
1611     if (parm_ich) {
1612         TPUTS_TRACE("parm_ich");
1613         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1614                                 TPARM_1(parm_ich, count),
1615                                 count,
1616                                 NCURSES_SP_NAME(_nc_outch));
1617         while (count) {
1618             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1619             line++;
1620             count--;
1621         }
1622     } else if (enter_insert_mode && exit_insert_mode) {
1623         TPUTS_TRACE("enter_insert_mode");
1624         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx enter_insert_mode);
1625         while (count) {
1626             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1627             if (insert_padding) {
1628                 TPUTS_TRACE("insert_padding");
1629                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_padding);
1630             }
1631             line++;
1632             count--;
1633         }
1634         TPUTS_TRACE("exit_insert_mode");
1635         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_insert_mode);
1636     } else {
1637         while (count) {
1638             TPUTS_TRACE("insert_character");
1639             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_character);
1640             PutAttrChar(NCURSES_SP_ARGx CHREF(*line));
1641             if (insert_padding) {
1642                 TPUTS_TRACE("insert_padding");
1643                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_padding);
1644             }
1645             line++;
1646             count--;
1647         }
1648     }
1649     position_check(SP_PARM, SP_PARM->_cursrow, SP_PARM->_curscol, "InsStr");
1650 }
1651
1652 /*
1653 **      DelChar(count)
1654 **
1655 **      Delete count characters at current position
1656 **
1657 */
1658
1659 static void
1660 DelChar(NCURSES_SP_DCLx int count)
1661 {
1662     int n;
1663
1664     TR(TRACE_UPDATE, ("DelChar(%p, %d) called, position = (%ld,%ld)",
1665                       SP_PARM, count,
1666                       (long) NewScreen(SP_PARM)->_cury,
1667                       (long) NewScreen(SP_PARM)->_curx));
1668
1669     if (parm_dch) {
1670         TPUTS_TRACE("parm_dch");
1671         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1672                                 TPARM_1(parm_dch, count),
1673                                 count,
1674                                 NCURSES_SP_NAME(_nc_outch));
1675     } else {
1676         for (n = 0; n < count; n++) {
1677             TPUTS_TRACE("delete_character");
1678             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_character);
1679         }
1680     }
1681 }
1682
1683 /*
1684  * Physical-scrolling support
1685  *
1686  * This code was adapted from Keith Bostic's hardware scrolling
1687  * support for 4.4BSD curses.  I (esr) translated it to use terminfo
1688  * capabilities, narrowed the call interface slightly, and cleaned
1689  * up some convoluted tests.  I also added support for the memory_above
1690  * memory_below, and non_dest_scroll_region capabilities.
1691  *
1692  * For this code to work, we must have either
1693  * change_scroll_region and scroll forward/reverse commands, or
1694  * insert and delete line capabilities.
1695  * When the scrolling region has been set, the cursor has to
1696  * be at the last line of the region to make the scroll up
1697  * happen, or on the first line of region to scroll down.
1698  *
1699  * This code makes one aesthetic decision in the opposite way from
1700  * BSD curses.  BSD curses preferred pairs of il/dl operations
1701  * over scrolls, allegedly because il/dl looked faster.  We, on
1702  * the other hand, prefer scrolls because (a) they're just as fast
1703  * on many terminals and (b) using them avoids bouncing an
1704  * unchanged bottom section of the screen up and down, which is
1705  * visually nasty.
1706  *
1707  * (lav): added more cases, used dl/il when bot==maxy and in csr case.
1708  *
1709  * I used assumption that capabilities il/il1/dl/dl1 work inside
1710  * changed scroll region not shifting screen contents outside of it.
1711  * If there are any terminals behaving different way, it would be
1712  * necessary to add some conditions to scroll_csr_forward/backward.
1713  */
1714
1715 /* Try to scroll up assuming given csr (miny, maxy). Returns ERR on failure */
1716 static int
1717 scroll_csr_forward(NCURSES_SP_DCLx
1718                    int n,
1719                    int top,
1720                    int bot,
1721                    int miny,
1722                    int maxy,
1723                    NCURSES_CH_T blank)
1724 {
1725     int i;
1726
1727     if (n == 1 && scroll_forward && top == miny && bot == maxy) {
1728         GoTo(NCURSES_SP_ARGx bot, 0);
1729         UpdateAttrs(SP_PARM, blank);
1730         TPUTS_TRACE("scroll_forward");
1731         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_forward);
1732     } else if (n == 1 && delete_line && bot == maxy) {
1733         GoTo(NCURSES_SP_ARGx top, 0);
1734         UpdateAttrs(SP_PARM, blank);
1735         TPUTS_TRACE("delete_line");
1736         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1737     } else if (parm_index && top == miny && bot == maxy) {
1738         GoTo(NCURSES_SP_ARGx bot, 0);
1739         UpdateAttrs(SP_PARM, blank);
1740         TPUTS_TRACE("parm_index");
1741         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1742                                 TPARM_2(parm_index, n, 0),
1743                                 n,
1744                                 NCURSES_SP_NAME(_nc_outch));
1745     } else if (parm_delete_line && bot == maxy) {
1746         GoTo(NCURSES_SP_ARGx top, 0);
1747         UpdateAttrs(SP_PARM, blank);
1748         TPUTS_TRACE("parm_delete_line");
1749         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1750                                 TPARM_2(parm_delete_line, n, 0),
1751                                 n,
1752                                 NCURSES_SP_NAME(_nc_outch));
1753     } else if (scroll_forward && top == miny && bot == maxy) {
1754         GoTo(NCURSES_SP_ARGx bot, 0);
1755         UpdateAttrs(SP_PARM, blank);
1756         for (i = 0; i < n; i++) {
1757             TPUTS_TRACE("scroll_forward");
1758             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_forward);
1759         }
1760     } else if (delete_line && bot == maxy) {
1761         GoTo(NCURSES_SP_ARGx top, 0);
1762         UpdateAttrs(SP_PARM, blank);
1763         for (i = 0; i < n; i++) {
1764             TPUTS_TRACE("delete_line");
1765             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1766         }
1767     } else
1768         return ERR;
1769
1770 #if NCURSES_EXT_FUNCS
1771     if (FILL_BCE(SP_PARM)) {
1772         int j;
1773         for (i = 0; i < n; i++) {
1774             GoTo(NCURSES_SP_ARGx bot - i, 0);
1775             for (j = 0; j < screen_columns(SP_PARM); j++)
1776                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1777         }
1778     }
1779 #endif
1780     return OK;
1781 }
1782
1783 /* Try to scroll down assuming given csr (miny, maxy). Returns ERR on failure */
1784 /* n > 0 */
1785 static int
1786 scroll_csr_backward(NCURSES_SP_DCLx
1787                     int n,
1788                     int top,
1789                     int bot,
1790                     int miny,
1791                     int maxy,
1792                     NCURSES_CH_T blank)
1793 {
1794     int i;
1795
1796     if (n == 1 && scroll_reverse && top == miny && bot == maxy) {
1797         GoTo(NCURSES_SP_ARGx top, 0);
1798         UpdateAttrs(SP_PARM, blank);
1799         TPUTS_TRACE("scroll_reverse");
1800         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_reverse);
1801     } else if (n == 1 && insert_line && bot == maxy) {
1802         GoTo(NCURSES_SP_ARGx top, 0);
1803         UpdateAttrs(SP_PARM, blank);
1804         TPUTS_TRACE("insert_line");
1805         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1806     } else if (parm_rindex && top == miny && bot == maxy) {
1807         GoTo(NCURSES_SP_ARGx top, 0);
1808         UpdateAttrs(SP_PARM, blank);
1809         TPUTS_TRACE("parm_rindex");
1810         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1811                                 TPARM_2(parm_rindex, n, 0),
1812                                 n,
1813                                 NCURSES_SP_NAME(_nc_outch));
1814     } else if (parm_insert_line && bot == maxy) {
1815         GoTo(NCURSES_SP_ARGx top, 0);
1816         UpdateAttrs(SP_PARM, blank);
1817         TPUTS_TRACE("parm_insert_line");
1818         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1819                                 TPARM_2(parm_insert_line, n, 0),
1820                                 n,
1821                                 NCURSES_SP_NAME(_nc_outch));
1822     } else if (scroll_reverse && top == miny && bot == maxy) {
1823         GoTo(NCURSES_SP_ARGx top, 0);
1824         UpdateAttrs(SP_PARM, blank);
1825         for (i = 0; i < n; i++) {
1826             TPUTS_TRACE("scroll_reverse");
1827             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx scroll_reverse);
1828         }
1829     } else if (insert_line && bot == maxy) {
1830         GoTo(NCURSES_SP_ARGx top, 0);
1831         UpdateAttrs(SP_PARM, blank);
1832         for (i = 0; i < n; i++) {
1833             TPUTS_TRACE("insert_line");
1834             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1835         }
1836     } else
1837         return ERR;
1838
1839 #if NCURSES_EXT_FUNCS
1840     if (FILL_BCE(SP_PARM)) {
1841         int j;
1842         for (i = 0; i < n; i++) {
1843             GoTo(NCURSES_SP_ARGx top + i, 0);
1844             for (j = 0; j < screen_columns(SP_PARM); j++)
1845                 PutChar(NCURSES_SP_ARGx CHREF(blank));
1846         }
1847     }
1848 #endif
1849     return OK;
1850 }
1851
1852 /* scroll by using delete_line at del and insert_line at ins */
1853 /* n > 0 */
1854 static int
1855 scroll_idl(NCURSES_SP_DCLx int n, int del, int ins, NCURSES_CH_T blank)
1856 {
1857     int i;
1858
1859     if (!((parm_delete_line || delete_line) && (parm_insert_line || insert_line)))
1860         return ERR;
1861
1862     GoTo(NCURSES_SP_ARGx del, 0);
1863     UpdateAttrs(SP_PARM, blank);
1864     if (n == 1 && delete_line) {
1865         TPUTS_TRACE("delete_line");
1866         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1867     } else if (parm_delete_line) {
1868         TPUTS_TRACE("parm_delete_line");
1869         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1870                                 TPARM_2(parm_delete_line, n, 0),
1871                                 n,
1872                                 NCURSES_SP_NAME(_nc_outch));
1873     } else {                    /* if (delete_line) */
1874         for (i = 0; i < n; i++) {
1875             TPUTS_TRACE("delete_line");
1876             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx delete_line);
1877         }
1878     }
1879
1880     GoTo(NCURSES_SP_ARGx ins, 0);
1881     UpdateAttrs(SP_PARM, blank);
1882     if (n == 1 && insert_line) {
1883         TPUTS_TRACE("insert_line");
1884         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1885     } else if (parm_insert_line) {
1886         TPUTS_TRACE("parm_insert_line");
1887         NCURSES_SP_NAME(tputs) (NCURSES_SP_ARGx
1888                                 TPARM_2(parm_insert_line, n, 0),
1889                                 n,
1890                                 NCURSES_SP_NAME(_nc_outch));
1891     } else {                    /* if (insert_line) */
1892         for (i = 0; i < n; i++) {
1893             TPUTS_TRACE("insert_line");
1894             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx insert_line);
1895         }
1896     }
1897
1898     return OK;
1899 }
1900
1901 /*
1902  * Note:  some terminals require the cursor to be within the scrolling margins
1903  * before setting them.  Generally, the cursor must be at the appropriate end
1904  * of the scrolling margins when issuing an indexing operation (it is not
1905  * apparent whether it must also be at the left margin; we do this just to be
1906  * safe).  To make the related cursor movement a little faster, we use the
1907  * save/restore cursor capabilities if the terminal has them.
1908  */
1909 NCURSES_EXPORT(int)
1910 NCURSES_SP_NAME(_nc_scrolln) (NCURSES_SP_DCLx
1911                               int n,
1912                               int top,
1913                               int bot,
1914                               int maxy)
1915 /* scroll region from top to bot by n lines */
1916 {
1917     NCURSES_CH_T blank = ClrBlank(NCURSES_SP_ARGx StdScreen(SP_PARM));
1918     int i;
1919     bool cursor_saved = FALSE;
1920     int res;
1921
1922     TR(TRACE_MOVE, ("mvcur_scrolln(%d, %d, %d, %d)", n, top, bot, maxy));
1923
1924 #if USE_XMC_SUPPORT
1925     /*
1926      * If we scroll, we might remove a cookie.
1927      */
1928     if (magic_cookie_glitch > 0) {
1929         return (ERR);
1930     }
1931 #endif
1932
1933     if (n > 0) {                /* scroll up (forward) */
1934         /*
1935          * Explicitly clear if stuff pushed off top of region might
1936          * be saved by the terminal.
1937          */
1938         res = scroll_csr_forward(NCURSES_SP_ARGx n, top, bot, 0, maxy, blank);
1939
1940         if (res == ERR && change_scroll_region) {
1941             if ((((n == 1 && scroll_forward) || parm_index)
1942                  && (SP_PARM->_cursrow == bot || SP_PARM->_cursrow == bot - 1))
1943                 && save_cursor && restore_cursor) {
1944                 cursor_saved = TRUE;
1945                 TPUTS_TRACE("save_cursor");
1946                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx save_cursor);
1947             }
1948             TPUTS_TRACE("change_scroll_region");
1949             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
1950                                    TPARM_2(change_scroll_region, top, bot));
1951             if (cursor_saved) {
1952                 TPUTS_TRACE("restore_cursor");
1953                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx restore_cursor);
1954             } else {
1955                 SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1956             }
1957
1958             res = scroll_csr_forward(NCURSES_SP_ARGx n, top, bot, top, bot, blank);
1959
1960             TPUTS_TRACE("change_scroll_region");
1961             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
1962                                    TPARM_2(change_scroll_region, 0, maxy));
1963             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
1964         }
1965
1966         if (res == ERR && _nc_idlok)
1967             res = scroll_idl(NCURSES_SP_ARGx n, top, bot - n + 1, blank);
1968
1969         /*
1970          * Clear the newly shifted-in text.
1971          */
1972         if (res != ERR
1973             && (non_dest_scroll_region || (memory_below && bot == maxy))) {
1974             static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
1975             if (bot == maxy && clr_eos) {
1976                 GoTo(NCURSES_SP_ARGx bot - n + 1, 0);
1977                 ClrToEOS(NCURSES_SP_ARGx blank2);
1978             } else {
1979                 for (i = 0; i < n; i++) {
1980                     GoTo(NCURSES_SP_ARGx bot - i, 0);
1981                     ClrToEOL(NCURSES_SP_ARGx blank2, FALSE);
1982                 }
1983             }
1984         }
1985
1986     } else {                    /* (n < 0) - scroll down (backward) */
1987         res = scroll_csr_backward(NCURSES_SP_ARGx -n, top, bot, 0, maxy, blank);
1988
1989         if (res == ERR && change_scroll_region) {
1990             if (top != 0
1991                 && (SP_PARM->_cursrow == top ||
1992                     SP_PARM->_cursrow == top - 1)
1993                 && save_cursor && restore_cursor) {
1994                 cursor_saved = TRUE;
1995                 TPUTS_TRACE("save_cursor");
1996                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx save_cursor);
1997             }
1998             TPUTS_TRACE("change_scroll_region");
1999             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
2000                                    TPARM_2(change_scroll_region, top, bot));
2001             if (cursor_saved) {
2002                 TPUTS_TRACE("restore_cursor");
2003                 NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx restore_cursor);
2004             } else {
2005                 SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2006             }
2007
2008             res = scroll_csr_backward(NCURSES_SP_ARGx
2009                                       -n, top, bot, top, bot, blank);
2010
2011             TPUTS_TRACE("change_scroll_region");
2012             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
2013                                    TPARM_2(change_scroll_region, 0, maxy));
2014             SP_PARM->_cursrow = SP_PARM->_curscol = -1;
2015         }
2016
2017         if (res == ERR && _nc_idlok)
2018             res = scroll_idl(NCURSES_SP_ARGx -n, bot + n + 1, top, blank);
2019
2020         /*
2021          * Clear the newly shifted-in text.
2022          */
2023         if (res != ERR
2024             && (non_dest_scroll_region || (memory_above && top == 0))) {
2025             static const NCURSES_CH_T blank2 = NewChar(BLANK_TEXT);
2026             for (i = 0; i < -n; i++) {
2027                 GoTo(NCURSES_SP_ARGx i + top, 0);
2028                 ClrToEOL(NCURSES_SP_ARGx blank2, FALSE);
2029             }
2030         }
2031     }
2032
2033     if (res == ERR)
2034         return (ERR);
2035
2036     _nc_scroll_window(CurScreen(SP_PARM), n, top, bot, blank);
2037
2038     /* shift hash values too - they can be reused */
2039     NCURSES_SP_NAME(_nc_scroll_oldhash) (NCURSES_SP_ARGx n, top, bot);
2040
2041     return (OK);
2042 }
2043
2044 #if NCURSES_SP_FUNCS
2045 NCURSES_EXPORT(int)
2046 _nc_scrolln(int n, int top, int bot, int maxy)
2047 {
2048     return NCURSES_SP_NAME(_nc_scrolln) (CURRENT_SCREEN, n, top, bot, maxy);
2049 }
2050 #endif
2051
2052 NCURSES_EXPORT(void)
2053 NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_DCL0)
2054 {
2055     assert(SP_PARM);
2056
2057     /* make sure terminal is in a sane known state */
2058     SetAttr(SCREEN_ATTRS(SP_PARM), A_NORMAL);
2059     NewScreen(SP_PARM)->_clear = TRUE;
2060
2061     /* reset color pairs and definitions */
2062     if (SP_PARM->_coloron || SP_PARM->_color_defs)
2063         _nc_reset_colors();
2064
2065     /* restore user-defined colors, if any */
2066     if (SP_PARM->_color_defs < 0) {
2067         int n;
2068         SP_PARM->_color_defs = -(SP_PARM->_color_defs);
2069         for (n = 0; n < SP_PARM->_color_defs; ++n) {
2070             if (SP_PARM->_color_table[n].init) {
2071                 NCURSES_SP_NAME(init_color) (NCURSES_SP_ARGx n,
2072                                              SP_PARM->_color_table[n].r,
2073                                              SP_PARM->_color_table[n].g,
2074                                              SP_PARM->_color_table[n].b);
2075             }
2076         }
2077     }
2078
2079     if (exit_attribute_mode)
2080         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_attribute_mode);
2081     else {
2082         /* turn off attributes */
2083         if (exit_alt_charset_mode)
2084             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_alt_charset_mode);
2085         if (exit_standout_mode)
2086             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_standout_mode);
2087         if (exit_underline_mode)
2088             NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_underline_mode);
2089     }
2090     if (exit_insert_mode)
2091         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx exit_insert_mode);
2092     if (enter_am_mode && exit_am_mode)
2093         NCURSES_SP_NAME(putp) (NCURSES_SP_ARGx
2094                                (auto_right_margin
2095                                 ? enter_am_mode
2096                                 : exit_am_mode));
2097 }
2098
2099 #if NCURSES_SP_FUNCS
2100 NCURSES_EXPORT(void)
2101 _nc_screen_resume(void)
2102 {
2103     NCURSES_SP_NAME(_nc_screen_resume) (CURRENT_SCREEN);
2104 }
2105 #endif
2106
2107 NCURSES_EXPORT(void)
2108 NCURSES_SP_NAME(_nc_screen_init) (NCURSES_SP_DCL0)
2109 {
2110     NCURSES_SP_NAME(_nc_screen_resume) (NCURSES_SP_ARG);
2111 }
2112
2113 #if NCURSES_SP_FUNCS
2114 NCURSES_EXPORT(void)
2115 _nc_screen_init(void)
2116 {
2117     NCURSES_SP_NAME(_nc_screen_init) (CURRENT_SCREEN);
2118 }
2119 #endif
2120
2121 /* wrap up screen handling */
2122 NCURSES_EXPORT(void)
2123 NCURSES_SP_NAME(_nc_screen_wrap) (NCURSES_SP_DCL0)
2124 {
2125     if (SP_PARM == 0)
2126         return;
2127
2128     UpdateAttrs(SP_PARM, normal);
2129 #if NCURSES_EXT_FUNCS
2130     if (SP_PARM->_coloron
2131         && !SP_PARM->_default_color) {
2132         static const NCURSES_CH_T blank = NewChar(BLANK_TEXT);
2133         SP_PARM->_default_color = TRUE;
2134         NCURSES_SP_NAME(_nc_do_color) (NCURSES_SP_ARGx
2135                                        -1, 0,
2136                                        FALSE,
2137                                        NCURSES_SP_NAME(_nc_outch));
2138         SP_PARM->_default_color = FALSE;
2139
2140         mvcur(SP_PARM->_cursrow,
2141               SP_PARM->_curscol,
2142               screen_lines(SP_PARM) - 1, 0);
2143
2144         ClrToEOL(NCURSES_SP_ARGx blank, TRUE);
2145     }
2146 #endif
2147     if (SP_PARM->_color_defs) {
2148         _nc_reset_colors();
2149     }
2150 }
2151
2152 #if NCURSES_SP_FUNCS
2153 NCURSES_EXPORT(void)
2154 _nc_screen_wrap(void)
2155 {
2156     NCURSES_SP_NAME(_nc_screen_wrap) (CURRENT_SCREEN);
2157 }
2158 #endif
2159
2160 #if USE_XMC_SUPPORT
2161 NCURSES_EXPORT(void)
2162 NCURSES_SP_NAME(_nc_do_xmc_glitch) (NCURSES_SP_DCLx attr_t previous)
2163 {
2164     if (SP_PARM != 0) {
2165         attr_t chg = XMC_CHANGES(previous ^ AttrOf(SCREEN_ATTRS(SP_PARM)));
2166
2167         while (chg != 0) {
2168             if (chg & 1) {
2169                 SP_PARM->_curscol += magic_cookie_glitch;
2170                 if (SP_PARM->_curscol >= SP_PARM->_columns)
2171                     wrap_cursor(NCURSES_SP_ARG);
2172                 TR(TRACE_UPDATE, ("bumped to %d,%d after cookie",
2173                                   SP_PARM->_cursrow, SP_PARM->_curscol));
2174             }
2175             chg >>= 1;
2176         }
2177     }
2178 }
2179
2180 #if NCURSES_SP_FUNCS
2181 NCURSES_EXPORT(void)
2182 _nc_do_xmc_glitch(attr_t previous)
2183 {
2184     NCURSES_SP_NAME(_nc_do_xmc_glitch) (CURRENT_SCREEN, previous);
2185 }
2186 #endif
2187
2188 #endif /* USE_XMC_SUPPORT */