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