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