1 /****************************************************************************
2  * Copyright 2019,2020 Thomas E. Dickey                                     *
3  * Copyright 1998-2016,2017 Free Software Foundation, Inc.                  *
4  *                                                                          *
5  * Permission is hereby granted, free of charge, to any person obtaining a  *
6  * copy of this software and associated documentation files (the            *
7  * "Software"), to deal in the Software without restriction, including      *
8  * without limitation the rights to use, copy, modify, merge, publish,      *
9  * distribute, distribute with modifications, sublicense, and/or sell       *
10  * copies of the Software, and to permit persons to whom the Software is    *
11  * furnished to do so, subject to the following conditions:                 *
12  *                                                                          *
13  * The above copyright notice and this permission notice shall be included  *
14  * in all copies or substantial portions of the Software.                   *
15  *                                                                          *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS  *
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF               *
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.   *
19  * IN NO EVENT SHALL THE ABOVE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,   *
20  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR    *
21  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR    *
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.                               *
23  *                                                                          *
24  * Except as contained in this notice, the name(s) of the above copyright   *
25  * holders shall not be used in advertising or otherwise to promote the     *
26  * sale, use or other dealings in this Software without prior written       *
27  * authorization.                                                           *
28  ****************************************************************************/
29 
30 /*
31 **	lib_addch.c
32 **
33 **	The routine waddch().
34 **
35 */
36 
37 #include <curses.priv.h>
38 #include <ctype.h>
39 
40 MODULE_ID("$Id: lib_addch.c,v 1.134 2020/02/02 23:34:34 tom Exp $")
41 
42 static const NCURSES_CH_T blankchar = NewChar(BLANK_TEXT);
43 
44 /*
45  * Ugly microtweaking alert.  Everything from here to end of module is
46  * likely to be speed-critical -- profiling data sure says it is!
47  * Most of the important screen-painting functions are shells around
48  * waddch().  So we make every effort to reduce function-call overhead
49  * by inlining stuff, even at the cost of making wrapped copies for
50  * export.  Also we supply some internal versions that don't call the
51  * window sync hook, for use by string-put functions.
52  */
53 
54 /* Return bit mask for clearing color pair number if given ch has color */
55 #define COLOR_MASK(ch) (~(attr_t)(((ch) & A_COLOR) ? A_COLOR : 0))
56 
57 static NCURSES_INLINE NCURSES_CH_T
58 render_char(WINDOW *win, NCURSES_CH_T ch)
59 /* compute a rendition of the given char correct for the current context */
60 {
61     attr_t a = WINDOW_ATTRS(win);
62     int pair = GetPair(ch);
63 
64     if (ISBLANK(ch)
65 	&& AttrOf(ch) == A_NORMAL
66 	&& pair == 0) {
67 	/* color/pair in attrs has precedence over bkgrnd */
68 	ch = win->_nc_bkgd;
69 	SetAttr(ch, a | AttrOf(win->_nc_bkgd));
70 	if ((pair = GET_WINDOW_PAIR(win)) == 0)
71 	    pair = GetPair(win->_nc_bkgd);
72 	SetPair(ch, pair);
73     } else {
74 	/* color in attrs has precedence over bkgrnd */
75 	a |= AttrOf(win->_nc_bkgd) & COLOR_MASK(a);
76 	/* color in ch has precedence */
77 	if (pair == 0) {
78 	    if ((pair = GET_WINDOW_PAIR(win)) == 0)
79 		pair = GetPair(win->_nc_bkgd);
80 	}
81 	AddAttr(ch, (a & COLOR_MASK(AttrOf(ch))));
82 	SetPair(ch, pair);
83     }
84 
85     TR(TRACE_VIRTPUT,
86        ("render_char bkg %s (%d), attrs %s (%d) -> ch %s (%d)",
87 	_tracech_t2(1, CHREF(win->_nc_bkgd)),
88 	GetPair(win->_nc_bkgd),
89 	_traceattr(WINDOW_ATTRS(win)),
90 	GET_WINDOW_PAIR(win),
91 	_tracech_t2(3, CHREF(ch)),
92 	GetPair(ch)));
93 
94     return (ch);
95 }
96 
97 NCURSES_EXPORT(NCURSES_CH_T)
98 _nc_render(WINDOW *win, NCURSES_CH_T ch)
99 /* make render_char() visible while still allowing us to inline it below */
100 {
101     return render_char(win, ch);
102 }
103 
104 /* check if position is legal; if not, return error */
105 #ifndef NDEBUG			/* treat this like an assertion */
106 #define CHECK_POSITION(win, x, y) \
107 	if (y > win->_maxy \
108 	 || x > win->_maxx \
109 	 || y < 0 \
110 	 || x < 0) { \
111 		TR(TRACE_VIRTPUT, ("Alert! Win=%p _curx = %d, _cury = %d " \
112 				   "(_maxx = %d, _maxy = %d)", win, x, y, \
113 				   win->_maxx, win->_maxy)); \
114 		return(ERR); \
115 	}
116 #else
117 #define CHECK_POSITION(win, x, y)	/* nothing */
118 #endif
119 
120 static bool
121 newline_forces_scroll(WINDOW *win, NCURSES_SIZE_T *ypos)
122 {
123     bool result = FALSE;
124 
125     if (*ypos >= win->_regtop && *ypos <= win->_regbottom) {
126 	if (*ypos == win->_regbottom) {
127 	    *ypos = win->_regbottom;
128 	    result = TRUE;
129 	} else if (*ypos < win->_maxy) {
130 	    *ypos = (NCURSES_SIZE_T) (*ypos + 1);
131 	}
132     } else if (*ypos < win->_maxy) {
133 	*ypos = (NCURSES_SIZE_T) (*ypos + 1);
134     }
135     return result;
136 }
137 
138 /*
139  * The _WRAPPED flag is useful only for telling an application that we've just
140  * wrapped the cursor.  We don't do anything with this flag except set it when
141  * wrapping, and clear it whenever we move the cursor.  If we try to wrap at
142  * the lower-right corner of a window, we cannot move the cursor (since that
143  * wouldn't be legal).  So we return an error (which is what SVr4 does).
144  * Unlike SVr4, we can successfully add a character to the lower-right corner
145  * (Solaris 2.6 does this also, however).
146  */
147 static int
148 wrap_to_next_line(WINDOW *win)
149 {
150     win->_flags |= _WRAPPED;
151     if (newline_forces_scroll(win, &(win->_cury))) {
152 	win->_curx = win->_maxx;
153 	if (!win->_scroll)
154 	    return (ERR);
155 	scroll(win);
156     }
157     win->_curx = 0;
158     return (OK);
159 }
160 
161 #if USE_WIDEC_SUPPORT
162 static int waddch_literal(WINDOW *, NCURSES_CH_T);
163 /*
164  * Fill the given number of cells with blanks using the current background
165  * rendition.  This saves/restores the current x-position.
166  */
167 static void
168 fill_cells(WINDOW *win, int count)
169 {
170     NCURSES_CH_T blank = blankchar;
171     int save_x = win->_curx;
172     int save_y = win->_cury;
173 
174     while (count-- > 0) {
175 	if (waddch_literal(win, blank) == ERR)
176 	    break;
177     }
178     win->_curx = (NCURSES_SIZE_T) save_x;
179     win->_cury = (NCURSES_SIZE_T) save_y;
180 }
181 #endif
182 
183 /*
184  * Build up the bytes for a multibyte character, returning the length when
185  * complete (a positive number), -1 for error and -2 for incomplete.
186  */
187 #if USE_WIDEC_SUPPORT
188 NCURSES_EXPORT(int)
189 _nc_build_wch(WINDOW *win, ARG_CH_T ch)
190 {
191     char *buffer = WINDOW_EXT(win, addch_work);
192     int len;
193     int x = win->_curx;
194     int y = win->_cury;
195     mbstate_t state;
196     wchar_t result;
197 
198     if ((WINDOW_EXT(win, addch_used) != 0) &&
199 	(WINDOW_EXT(win, addch_x) != x ||
200 	 WINDOW_EXT(win, addch_y) != y)) {
201 	/* discard the incomplete multibyte character */
202 	WINDOW_EXT(win, addch_used) = 0;
203 	TR(TRACE_VIRTPUT,
204 	   ("Alert discarded multibyte on move (%d,%d) -> (%d,%d)",
205 	    WINDOW_EXT(win, addch_y), WINDOW_EXT(win, addch_x),
206 	    y, x));
207     }
208     WINDOW_EXT(win, addch_x) = x;
209     WINDOW_EXT(win, addch_y) = y;
210 
211     init_mb(state);
212     buffer[WINDOW_EXT(win, addch_used)] = (char) CharOf(CHDEREF(ch));
213     WINDOW_EXT(win, addch_used) += 1;
214     buffer[WINDOW_EXT(win, addch_used)] = '\0';
215     if ((len = (int) mbrtowc(&result,
216 			     buffer,
217 			     (size_t) WINDOW_EXT(win, addch_used),
218 			     &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 NCURSES_SP_FUNCS
264 #define DeriveSP() SCREEN *sp = _nc_screen_of(win);
265 #else
266 #define DeriveSP()		/*nothing */
267 #endif
268     if_WIDEC({
269 	DeriveSP();
270 	if (WINDOW_EXT(win, addch_used) != 0 || !Charable(ch)) {
271 	    int len = _nc_build_wch(win, CHREF(ch));
272 
273 	    if (len >= -1) {
274 		attr_t attr = AttrOf(ch);
275 
276 		/* handle EILSEQ (i.e., when len >= -1) */
277 		if (len == -1 && is8bits(CharOf(ch))) {
278 		    const char *s = NCURSES_SP_NAME(unctrl)
279 		      (NCURSES_SP_ARGx (chtype) CharOf(ch));
280 
281 		    if (s[1] != '\0') {
282 			int rc = OK;
283 			while (*s != '\0') {
284 			    rc = waddch(win, UChar(*s) | attr);
285 			    if (rc != OK)
286 				break;
287 			    ++s;
288 			}
289 			return rc;
290 		    }
291 		}
292 		if (len == -1)
293 		    return waddch(win, ' ' | attr);
294 	    } else {
295 		return OK;
296 	    }
297 	}
298     });
299 
300     /*
301      * Non-spacing characters are added to the current cell.
302      *
303      * Spacing characters that are wider than one column require some display
304      * adjustments.
305      */
306     if_WIDEC({
307 	int len = _nc_wacs_width(CharOf(ch));
308 	int i;
309 	int j;
310 	wchar_t *chars;
311 
312 	if (len == 0) {		/* non-spacing */
313 	    if ((x > 0 && y >= 0)
314 		|| (win->_maxx >= 0 && win->_cury >= 1)) {
315 		if (x > 0 && y >= 0)
316 		    chars = (win->_line[y].text[x - 1].chars);
317 		else
318 		    chars = (win->_line[y - 1].text[win->_maxx].chars);
319 		for (i = 0; i < CCHARW_MAX; ++i) {
320 		    if (chars[i] == 0) {
321 			TR(TRACE_VIRTPUT,
322 			   ("added non-spacing %d: %x",
323 			    x, (int) CharOf(ch)));
324 			chars[i] = CharOf(ch);
325 			break;
326 		    }
327 		}
328 	    }
329 	    goto testwrapping;
330 	} else if (len > 1) {	/* multi-column characters */
331 	    /*
332 	     * Check if the character will fit on the current line.  If it does
333 	     * not fit, fill in the remainder of the line with blanks.  and
334 	     * move to the next line.
335 	     */
336 	    if (len > win->_maxx + 1) {
337 		TR(TRACE_VIRTPUT, ("character will not fit"));
338 		return ERR;
339 	    } else if (x + len > win->_maxx + 1) {
340 		int count = win->_maxx + 1 - x;
341 		TR(TRACE_VIRTPUT, ("fill %d remaining cells", count));
342 		fill_cells(win, count);
343 		if (wrap_to_next_line(win) == ERR)
344 		    return ERR;
345 		x = win->_curx;
346 		y = win->_cury;
347 		CHECK_POSITION(win, x, y);
348 		line = win->_line + y;
349 	    }
350 	    /*
351 	     * Check for cells which are orphaned by adding this character, set
352 	     * those to blanks.
353 	     *
354 	     * FIXME: this actually could fill j-i cells, more complicated to
355 	     * setup though.
356 	     */
357 	    for (i = 0; i < len; ++i) {
358 		if (isWidecBase(win->_line[y].text[x + i])) {
359 		    break;
360 		} else if (isWidecExt(win->_line[y].text[x + i])) {
361 		    for (j = i; x + j <= win->_maxx; ++j) {
362 			if (!isWidecExt(win->_line[y].text[x + j])) {
363 			    TR(TRACE_VIRTPUT, ("fill %d orphan cells", j));
364 			    fill_cells(win, j);
365 			    break;
366 			}
367 		    }
368 		    break;
369 		}
370 	    }
371 	    /*
372 	     * Finally, add the cells for this character.
373 	     */
374 	    for (i = 0; i < len; ++i) {
375 		NCURSES_CH_T value = ch;
376 		SetWidecExt(value, i);
377 		TR(TRACE_VIRTPUT, ("multicolumn %d:%d (%d,%d)",
378 				   i + 1, len,
379 				   win->_begy + y, win->_begx + x));
380 		line->text[x] = value;
381 		CHANGED_CELL(line, x);
382 		++x;
383 	    }
384 	    goto testwrapping;
385 	}
386     });
387 
388     /*
389      * Single-column characters.
390      */
391     line->text[x++] = ch;
392     /*
393      * This label is used only for wide-characters.
394      */
395     if_WIDEC(
396   testwrapping:
397     );
398 
399     TR(TRACE_VIRTPUT, ("cell (%ld, %ld..%d) = %s",
400 		       (long) win->_cury, (long) win->_curx, x - 1,
401 		       _tracech_t(CHREF(ch))));
402 
403     if (x > win->_maxx) {
404 	return wrap_to_next_line(win);
405     }
406     win->_curx = (NCURSES_SIZE_T) x;
407     return OK;
408 }
409 
410 static NCURSES_INLINE int
411 waddch_nosync(WINDOW *win, const NCURSES_CH_T ch)
412 /* the workhorse function -- add a character to the given window */
413 {
414     NCURSES_SIZE_T x, y;
415     chtype t = (chtype) CharOf(ch);
416 #if USE_WIDEC_SUPPORT || NCURSES_SP_FUNCS || USE_REENTRANT
417     SCREEN *sp = _nc_screen_of(win);
418 #endif
419     const char *s = NCURSES_SP_NAME(unctrl) (NCURSES_SP_ARGx t);
420     int tabsize = 8;
421 
422     /*
423      * If we are using the alternate character set, forget about locale.
424      * Otherwise, if unctrl() returns a single-character or the locale
425      * claims the code is printable (and not also a control character),
426      * treat it that way.
427      */
428     if ((AttrOf(ch) & A_ALTCHARSET)
429 	|| (
430 #if USE_WIDEC_SUPPORT
431 	       (sp != 0 && sp->_legacy_coding) &&
432 #endif
433 	       s[1] == 0
434 	)
435 	|| (
436 	       (isprint((int) t) && !iscntrl((int) t))
437 #if USE_WIDEC_SUPPORT
438 	       || ((sp == 0 || !sp->_legacy_coding) &&
439 		   (WINDOW_EXT(win, addch_used)
440 		    || !_nc_is_charable(CharOf(ch))))
441 #endif
442 	)) {
443 	return waddch_literal(win, ch);
444     }
445 
446     /*
447      * Handle carriage control and other codes that are not printable, or are
448      * known to expand to more than one character according to unctrl().
449      */
450     x = win->_curx;
451     y = win->_cury;
452     CHECK_POSITION(win, x, y);
453 
454     switch (t) {
455     case '\t':
456 #if USE_REENTRANT
457 	tabsize = *ptrTabsize(sp);
458 #else
459 	tabsize = TABSIZE;
460 #endif
461 	x = (NCURSES_SIZE_T) (x + (tabsize - (x % tabsize)));
462 	/*
463 	 * Space-fill the tab on the bottom line so that we'll get the
464 	 * "correct" cursor position.
465 	 */
466 	if ((!win->_scroll && (y == win->_regbottom))
467 	    || (x <= win->_maxx)) {
468 	    NCURSES_CH_T blank = blankchar;
469 	    AddAttr(blank, AttrOf(ch));
470 	    while (win->_curx < x) {
471 		if (waddch_literal(win, blank) == ERR)
472 		    return (ERR);
473 	    }
474 	    break;
475 	} else {
476 	    wclrtoeol(win);
477 	    win->_flags |= _WRAPPED;
478 	    if (newline_forces_scroll(win, &y)) {
479 		x = win->_maxx;
480 		if (win->_scroll) {
481 		    scroll(win);
482 		    x = 0;
483 		}
484 	    } else {
485 		x = 0;
486 	    }
487 	}
488 	break;
489     case '\n':
490 	wclrtoeol(win);
491 	if (newline_forces_scroll(win, &y)) {
492 	    if (win->_scroll)
493 		scroll(win);
494 	    else
495 		return (ERR);
496 	}
497 	/* FALLTHRU */
498     case '\r':
499 	x = 0;
500 	win->_flags &= ~_WRAPPED;
501 	break;
502     case '\b':
503 	if (x == 0)
504 	    return (OK);
505 	x--;
506 	win->_flags &= ~_WRAPPED;
507 	break;
508     default:
509 	while (*s) {
510 	    NCURSES_CH_T sch;
511 	    SetChar(sch, UChar(*s++), AttrOf(ch));
512 	    if_EXT_COLORS(SetPair(sch, GetPair(ch)));
513 	    if (waddch_literal(win, sch) == ERR)
514 		return ERR;
515 	}
516 	return (OK);
517     }
518 
519     win->_curx = x;
520     win->_cury = y;
521 
522     return (OK);
523 }
524 
525 NCURSES_EXPORT(int)
526 _nc_waddch_nosync(WINDOW *win, const NCURSES_CH_T c)
527 /* export copy of waddch_nosync() so the string-put functions can use it */
528 {
529     return (waddch_nosync(win, c));
530 }
531 
532 /*
533  * The versions below call _nc_synchook().  We wanted to avoid this in the
534  * version exported for string puts; they'll call _nc_synchook once at end
535  * of run.
536  */
537 
538 /* These are actual entry points */
539 
540 NCURSES_EXPORT(int)
541 waddch(WINDOW *win, const chtype ch)
542 {
543     int code = ERR;
544     NCURSES_CH_T wch;
545     SetChar2(wch, ch);
546 
547     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("waddch(%p, %s)"), (void *) win,
548 				      _tracechtype(ch)));
549 
550     if (win && (waddch_nosync(win, wch) != ERR)) {
551 	_nc_synchook(win);
552 	code = OK;
553     }
554 
555     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
556     return (code);
557 }
558 
559 NCURSES_EXPORT(int)
560 wechochar(WINDOW *win, const chtype ch)
561 {
562     int code = ERR;
563     NCURSES_CH_T wch;
564     SetChar2(wch, ch);
565 
566     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("wechochar(%p, %s)"),
567 				      (void *) win,
568 				      _tracechtype(ch)));
569 
570     if (win && (waddch_nosync(win, wch) != ERR)) {
571 	bool save_immed = win->_immed;
572 	win->_immed = TRUE;
573 	_nc_synchook(win);
574 	win->_immed = save_immed;
575 	code = OK;
576     }
577     TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
578     return (code);
579 }
580