]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_addch.c
ncurses 5.7 - patch 20081129
[ncurses.git] / ncurses / base / lib_addch.c
1 /****************************************************************************
2  * Copyright (c) 1998-2006,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 **      lib_addch.c
31 **
32 **      The routine waddch().
33 **
34 */
35
36 #include <curses.priv.h>
37 #include <ctype.h>
38
39 MODULE_ID("$Id: lib_addch.c,v 1.114 2008/11/29 21:02:10 tom Exp $")
40
41 static const NCURSES_CH_T blankchar = NewChar(BLANK_TEXT);
42
43 /*
44  * Ugly microtweaking alert.  Everything from here to end of module is
45  * likely to be speed-critical -- profiling data sure says it is!
46  * Most of the important screen-painting functions are shells around
47  * waddch().  So we make every effort to reduce function-call overhead
48  * by inlining stuff, even at the cost of making wrapped copies for
49  * export.  Also we supply some internal versions that don't call the
50  * window sync hook, for use by string-put functions.
51  */
52
53 /* Return bit mask for clearing color pair number if given ch has color */
54 #define COLOR_MASK(ch) (~(attr_t)((ch) & A_COLOR ? A_COLOR : 0))
55
56 static NCURSES_INLINE NCURSES_CH_T
57 render_char(WINDOW *win, NCURSES_CH_T ch)
58 /* compute a rendition of the given char correct for the current context */
59 {
60     attr_t a = WINDOW_ATTRS(win);
61     int pair = GetPair(ch);
62
63     if (ISBLANK(ch)
64         && AttrOf(ch) == A_NORMAL
65         && pair == 0) {
66         /* color/pair in attrs has precedence over bkgrnd */
67         ch = win->_nc_bkgd;
68         SetAttr(ch, a | AttrOf(win->_nc_bkgd));
69         if ((pair = GET_WINDOW_PAIR(win)) == 0)
70             pair = GetPair(win->_nc_bkgd);
71         SetPair(ch, pair);
72     } else {
73         /* color in attrs has precedence over bkgrnd */
74         a |= AttrOf(win->_nc_bkgd) & COLOR_MASK(a);
75         /* color in ch has precedence */
76         if (pair == 0) {
77             if ((pair = GET_WINDOW_PAIR(win)) == 0)
78                 pair = GetPair(win->_nc_bkgd);
79         }
80 #if 0
81         if (pair > 255) {
82             NCURSES_CH_T fixme = ch;
83             SetPair(fixme, pair);
84         }
85 #endif
86         AddAttr(ch, (a & COLOR_MASK(AttrOf(ch))));
87         SetPair(ch, pair);
88     }
89
90     TR(TRACE_VIRTPUT,
91        ("render_char bkg %s (%d), attrs %s (%d) -> ch %s (%d)",
92         _tracech_t2(1, CHREF(win->_nc_bkgd)),
93         GetPair(win->_nc_bkgd),
94         _traceattr(WINDOW_ATTRS(win)),
95         GET_WINDOW_PAIR(win),
96         _tracech_t2(3, CHREF(ch)),
97         GetPair(ch)));
98
99     return (ch);
100 }
101
102 NCURSES_EXPORT(NCURSES_CH_T)
103 _nc_render(WINDOW *win, NCURSES_CH_T ch)
104 /* make render_char() visible while still allowing us to inline it below */
105 {
106     return render_char(win, ch);
107 }
108
109 /* check if position is legal; if not, return error */
110 #ifndef NDEBUG                  /* treat this like an assertion */
111 #define CHECK_POSITION(win, x, y) \
112         if (y > win->_maxy \
113          || x > win->_maxx \
114          || y < 0 \
115          || x < 0) { \
116                 TR(TRACE_VIRTPUT, ("Alert! Win=%p _curx = %d, _cury = %d " \
117                                    "(_maxx = %d, _maxy = %d)", win, x, y, \
118                                    win->_maxx, win->_maxy)); \
119                 return(ERR); \
120         }
121 #else
122 #define CHECK_POSITION(win, x, y)       /* nothing */
123 #endif
124
125 static bool
126 newline_forces_scroll(WINDOW *win, NCURSES_SIZE_T * ypos)
127 {
128     bool result = FALSE;
129
130     if (*ypos >= win->_regtop && *ypos == win->_regbottom) {
131         *ypos = win->_regbottom;
132         result = TRUE;
133     } else {
134         *ypos += 1;
135     }
136     return result;
137 }
138
139 /*
140  * The _WRAPPED flag is useful only for telling an application that we've just
141  * wrapped the cursor.  We don't do anything with this flag except set it when
142  * wrapping, and clear it whenever we move the cursor.  If we try to wrap at
143  * the lower-right corner of a window, we cannot move the cursor (since that
144  * wouldn't be legal).  So we return an error (which is what SVr4 does). 
145  * Unlike SVr4, we can successfully add a character to the lower-right corner
146  * (Solaris 2.6 does this also, however).
147  */
148 static int
149 wrap_to_next_line(WINDOW *win)
150 {
151     win->_flags |= _WRAPPED;
152     if (newline_forces_scroll(win, &(win->_cury))) {
153         win->_curx = win->_maxx;
154         if (!win->_scroll)
155             return (ERR);
156         scroll(win);
157     }
158     win->_curx = 0;
159     return (OK);
160 }
161
162 #if USE_WIDEC_SUPPORT
163 static int waddch_literal(WINDOW *, NCURSES_CH_T);
164 /*
165  * Fill the given number of cells with blanks using the current background
166  * rendition.  This saves/restores the current x-position.
167  */
168 static void
169 fill_cells(WINDOW *win, int count)
170 {
171     NCURSES_CH_T blank = blankchar;
172     int save_x = win->_curx;
173     int save_y = win->_cury;
174
175     while (count-- > 0) {
176         if (waddch_literal(win, blank) == ERR)
177             break;
178     }
179     win->_curx = save_x;
180     win->_cury = save_y;
181 }
182 #endif
183
184 /*
185  * Build up the bytes for a multibyte character, returning the length when
186  * complete (a positive number), -1 for error and -2 for incomplete.
187  */
188 #if USE_WIDEC_SUPPORT
189 NCURSES_EXPORT(int)
190 _nc_build_wch(WINDOW *win, ARG_CH_T ch)
191 {
192     char *buffer = WINDOW_EXT(win, addch_work);
193     int len;
194     int x = win->_curx;
195     int y = win->_cury;
196     mbstate_t state;
197     wchar_t result;
198
199     if ((WINDOW_EXT(win, addch_used) != 0) &&
200         (WINDOW_EXT(win, addch_x) != x ||
201          WINDOW_EXT(win, addch_y) != y)) {
202         /* discard the incomplete multibyte character */
203         WINDOW_EXT(win, addch_used) = 0;
204         TR(TRACE_VIRTPUT,
205            ("Alert discarded multibyte on move (%d,%d) -> (%d,%d)",
206             WINDOW_EXT(win, addch_y), WINDOW_EXT(win, addch_x),
207             y, x));
208     }
209     WINDOW_EXT(win, addch_x) = x;
210     WINDOW_EXT(win, addch_y) = y;
211
212     init_mb(state);
213     buffer[WINDOW_EXT(win, addch_used)] = (char) CharOf(CHDEREF(ch));
214     WINDOW_EXT(win, addch_used) += 1;
215     buffer[WINDOW_EXT(win, addch_used)] = '\0';
216     if ((len = mbrtowc(&result,
217                        buffer,
218                        WINDOW_EXT(win, addch_used), &state)) > 0) {
219         attr_t attrs = AttrOf(CHDEREF(ch));
220         if_EXT_COLORS(int pair = GetPair(CHDEREF(ch)));
221         SetChar(CHDEREF(ch), result, attrs);
222         if_EXT_COLORS(SetPair(CHDEREF(ch), pair));
223         WINDOW_EXT(win, addch_used) = 0;
224     } else if (len == -1) {
225         /*
226          * An error occurred.  We could either discard everything,
227          * or assume that the error was in the previous input.
228          * Try the latter.
229          */
230         TR(TRACE_VIRTPUT, ("Alert! mbrtowc returns error"));
231         /* handle this with unctrl() */
232         WINDOW_EXT(win, addch_used) = 0;
233     }
234     return len;
235 }
236 #endif /* USE_WIDEC_SUPPORT */
237
238 static
239 #if !USE_WIDEC_SUPPORT          /* cannot be inline if it is recursive */
240 NCURSES_INLINE
241 #endif
242 int
243 waddch_literal(WINDOW *win, NCURSES_CH_T ch)
244 {
245     int x;
246     int y;
247     struct ldat *line;
248
249     x = win->_curx;
250     y = win->_cury;
251
252     CHECK_POSITION(win, x, y);
253
254     ch = render_char(win, ch);
255
256     line = win->_line + y;
257
258     CHANGED_CELL(line, x);
259
260     /*
261      * Build up multibyte characters until we have a wide-character.
262      */
263     if_WIDEC({
264         if (WINDOW_EXT(win, addch_used) != 0 || !Charable(ch)) {
265             int len = _nc_build_wch(win, CHREF(ch));
266
267             if (len >= -1) {
268                 attr_t attr = AttrOf(ch);
269
270                 /* handle EILSEQ (i.e., when len >= -1) */
271                 if (is8bits(CharOf(ch))) {
272                     int rc = OK;
273                     const char *s = unctrl((chtype) CharOf(ch));
274
275                     if (s[1] != '\0') {
276                         while (*s != '\0') {
277                             rc = waddch(win, UChar(*s) | attr);
278                             if (rc != OK)
279                                 break;
280                             ++s;
281                         }
282                         return rc;
283                     }
284                 }
285                 if (len == -1)
286                     return waddch(win, ' ' | attr);
287             } else {
288                 return OK;
289             }
290         }
291     });
292
293     /*
294      * Non-spacing characters are added to the current cell.
295      *
296      * Spacing characters that are wider than one column require some display
297      * adjustments.
298      */
299     if_WIDEC({
300         int len = wcwidth(CharOf(ch));
301         int i;
302         int j;
303         wchar_t *chars;
304
305         if (len == 0) {         /* non-spacing */
306             if ((x > 0 && y >= 0)
307                 || (win->_maxx >= 0 && win->_cury >= 1)) {
308                 if (x > 0 && y >= 0)
309                     chars = (win->_line[y].text[x - 1].chars);
310                 else
311                     chars = (win->_line[y - 1].text[win->_maxx].chars);
312                 for (i = 0; i < CCHARW_MAX; ++i) {
313                     if (chars[i] == 0) {
314                         TR(TRACE_VIRTPUT,
315                            ("added non-spacing %d: %x",
316                             x, (int) CharOf(ch)));
317                         chars[i] = CharOf(ch);
318                         break;
319                     }
320                 }
321             }
322             goto testwrapping;
323         } else if (len > 1) {   /* multi-column characters */
324             /*
325              * Check if the character will fit on the current line.  If it does
326              * not fit, fill in the remainder of the line with blanks.  and
327              * move to the next line.
328              */
329             if (len > win->_maxx + 1) {
330                 TR(TRACE_VIRTPUT, ("character will not fit"));
331                 return ERR;
332             } else if (x + len > win->_maxx + 1) {
333                 int count = win->_maxx + 1 - x;
334                 TR(TRACE_VIRTPUT, ("fill %d remaining cells", count));
335                 fill_cells(win, count);
336                 if (wrap_to_next_line(win) == ERR)
337                     return ERR;
338                 x = win->_curx;
339                 y = win->_cury;
340             }
341             /*
342              * Check for cells which are orphaned by adding this character, set
343              * those to blanks.
344              *
345              * FIXME: this actually could fill j-i cells, more complicated to
346              * setup though.
347              */
348             for (i = 0; i < len; ++i) {
349                 if (isWidecBase(win->_line[y].text[x + i])) {
350                     break;
351                 } else if (isWidecExt(win->_line[y].text[x + i])) {
352                     for (j = i; x + j <= win->_maxx; ++j) {
353                         if (!isWidecExt(win->_line[y].text[x + j])) {
354                             TR(TRACE_VIRTPUT, ("fill %d orphan cells", j));
355                             fill_cells(win, j);
356                             break;
357                         }
358                     }
359                     break;
360                 }
361             }
362             /*
363              * Finally, add the cells for this character.
364              */
365             for (i = 0; i < len; ++i) {
366                 NCURSES_CH_T value = ch;
367                 SetWidecExt(value, i);
368                 TR(TRACE_VIRTPUT, ("multicolumn %d:%d (%d,%d)",
369                                    i + 1, len,
370                                    win->_begy + y, win->_begx + x));
371                 line->text[x] = value;
372                 CHANGED_CELL(line, x);
373                 ++x;
374             }
375             goto testwrapping;
376         }
377     });
378
379     /*
380      * Single-column characters.
381      */
382     line->text[x++] = ch;
383     /*
384      * This label is used only for wide-characters.
385      */
386     if_WIDEC(
387   testwrapping:
388     );
389
390     TR(TRACE_VIRTPUT, ("cell (%ld, %ld..%d) = %s",
391                        (long) win->_cury, (long) win->_curx, x - 1,
392                        _tracech_t(CHREF(ch))));
393
394     if (x > win->_maxx) {
395         return wrap_to_next_line(win);
396     }
397     win->_curx = x;
398     return OK;
399 }
400
401 static NCURSES_INLINE int
402 waddch_nosync(WINDOW *win, const NCURSES_CH_T ch)
403 /* the workhorse function -- add a character to the given window */
404 {
405     NCURSES_SIZE_T x, y;
406     chtype t = CharOf(ch);
407     const char *s = unctrl(t);
408
409     /*
410      * If we are using the alternate character set, forget about locale.
411      * Otherwise, if unctrl() returns a single-character or the locale
412      * claims the code is printable, treat it that way.
413      */
414     if ((AttrOf(ch) & A_ALTCHARSET)
415         || (
416 #if USE_WIDEC_SUPPORT
417                (SP != 0 && SP->_legacy_coding) &&
418 #endif
419                s[1] == 0
420         )
421         || (
422                isprint(t)
423 #if USE_WIDEC_SUPPORT
424                || ((SP == 0 || !SP->_legacy_coding) &&
425                    (WINDOW_EXT(win, addch_used)
426                     || !_nc_is_charable(CharOf(ch))))
427 #endif
428         ))
429         return waddch_literal(win, ch);
430
431     /*
432      * Handle carriage control and other codes that are not printable, or are
433      * known to expand to more than one character according to unctrl().
434      */
435     x = win->_curx;
436     y = win->_cury;
437
438     switch (t) {
439     case '\t':
440         x += (TABSIZE - (x % TABSIZE));
441
442         /*
443          * Space-fill the tab on the bottom line so that we'll get the
444          * "correct" cursor position.
445          */
446         if ((!win->_scroll && (y == win->_regbottom))
447             || (x <= win->_maxx)) {
448             NCURSES_CH_T blank = blankchar;
449             AddAttr(blank, AttrOf(ch));
450             while (win->_curx < x) {
451                 if (waddch_literal(win, blank) == ERR)
452                     return (ERR);
453             }
454             break;
455         } else {
456             wclrtoeol(win);
457             win->_flags |= _WRAPPED;
458             if (newline_forces_scroll(win, &y)) {
459                 x = win->_maxx;
460                 if (win->_scroll) {
461                     scroll(win);
462                     x = 0;
463                 }
464             } else {
465                 x = 0;
466             }
467         }
468         break;
469     case '\n':
470         wclrtoeol(win);
471         if (newline_forces_scroll(win, &y)) {
472             if (win->_scroll)
473                 scroll(win);
474             else
475                 return (ERR);
476         }
477         /* FALLTHRU */
478     case '\r':
479         x = 0;
480         win->_flags &= ~_WRAPPED;
481         break;
482     case '\b':
483         if (x == 0)
484             return (OK);
485         x--;
486         win->_flags &= ~_WRAPPED;
487         break;
488     default:
489         while (*s) {
490             NCURSES_CH_T sch;
491             SetChar(sch, *s++, AttrOf(ch));
492             if_EXT_COLORS(SetPair(sch, GetPair(ch)));
493             if (waddch_literal(win, sch) == ERR)
494                 return ERR;
495         }
496         return (OK);
497     }
498
499     win->_curx = x;
500     win->_cury = y;
501
502     return (OK);
503 }
504
505 NCURSES_EXPORT(int)
506 _nc_waddch_nosync(WINDOW *win, const NCURSES_CH_T c)
507 /* export copy of waddch_nosync() so the string-put functions can use it */
508 {
509     return (waddch_nosync(win, c));
510 }
511
512 /*
513  * The versions below call _nc_synchook().  We wanted to avoid this in the
514  * version exported for string puts; they'll call _nc_synchook once at end
515  * of run.
516  */
517
518 /* These are actual entry points */
519
520 NCURSES_EXPORT(int)
521 waddch(WINDOW *win, const chtype ch)
522 {
523     int code = ERR;
524     NCURSES_CH_T wch;
525     SetChar2(wch, ch);
526
527     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("waddch(%p, %s)"), win,
528                                       _tracechtype(ch)));
529
530     if (win && (waddch_nosync(win, wch) != ERR)) {
531         _nc_synchook(win);
532         code = OK;
533     }
534
535     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
536     return (code);
537 }
538
539 NCURSES_EXPORT(int)
540 wechochar(WINDOW *win, const chtype ch)
541 {
542     int code = ERR;
543     NCURSES_CH_T wch;
544     SetChar2(wch, ch);
545
546     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("wechochar(%p, %s)"), win,
547                                       _tracechtype(ch)));
548
549     if (win && (waddch_nosync(win, wch) != ERR)) {
550         bool save_immed = win->_immed;
551         win->_immed = TRUE;
552         _nc_synchook(win);
553         win->_immed = save_immed;
554         code = OK;
555     }
556     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
557     return (code);
558 }