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