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