1/****************************************************************************
2 * Copyright 2019-2020,2021 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
40MODULE_ID("$Id: lib_addch.c,v 1.137 2021/02/20 22:24:34 tom Exp $")
41
42static 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
57static NCURSES_INLINE NCURSES_CH_T
58render_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
97NCURSES_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
120static bool
121newline_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 */
147static int
148wrap_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
162static 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 */
167static void
168fill_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
188NCURSES_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    /*
212     * If the background character is a wide-character, that may interfere with
213     * processing multibyte characters in this function.
214     */
215    if (!is8bits(CharOf(CHDEREF(ch)))) {
216	if (WINDOW_EXT(win, addch_used) != 0) {
217	    /* discard the incomplete multibyte character */
218	    WINDOW_EXT(win, addch_used) = 0;
219	    TR(TRACE_VIRTPUT,
220	       ("Alert discarded incomplete multibyte"));
221	}
222	return 1;
223    }
224
225    init_mb(state);
226    buffer[WINDOW_EXT(win, addch_used)] = (char) CharOf(CHDEREF(ch));
227    WINDOW_EXT(win, addch_used) += 1;
228    buffer[WINDOW_EXT(win, addch_used)] = '\0';
229    if ((len = (int) mbrtowc(&result,
230			     buffer,
231			     (size_t) WINDOW_EXT(win, addch_used),
232			     &state)) > 0) {
233	attr_t attrs = AttrOf(CHDEREF(ch));
234	if_EXT_COLORS(int pair = GetPair(CHDEREF(ch)));
235	SetChar(CHDEREF(ch), result, attrs);
236	if_EXT_COLORS(SetPair(CHDEREF(ch), pair));
237	WINDOW_EXT(win, addch_used) = 0;
238    } else if (len == -1) {
239	/*
240	 * An error occurred.  We could either discard everything,
241	 * or assume that the error was in the previous input.
242	 * Try the latter.
243	 */
244	TR(TRACE_VIRTPUT, ("Alert! mbrtowc returns error"));
245	/* handle this with unctrl() */
246	WINDOW_EXT(win, addch_used) = 0;
247    }
248    return len;
249}
250#endif /* USE_WIDEC_SUPPORT */
251
252static
253#if !USE_WIDEC_SUPPORT		/* cannot be inline if it is recursive */
254NCURSES_INLINE
255#endif
256int
257waddch_literal(WINDOW *win, NCURSES_CH_T ch)
258{
259    int x;
260    int y;
261    struct ldat *line;
262
263    x = win->_curx;
264    y = win->_cury;
265
266    CHECK_POSITION(win, x, y);
267
268    ch = render_char(win, ch);
269
270    line = win->_line + y;
271
272    CHANGED_CELL(line, x);
273
274    /*
275     * Build up multibyte characters until we have a wide-character.
276     */
277#if NCURSES_SP_FUNCS
278#define DeriveSP() SCREEN *sp = _nc_screen_of(win);
279#else
280#define DeriveSP()		/*nothing */
281#endif
282    if_WIDEC({
283	DeriveSP();
284	if (WINDOW_EXT(win, addch_used) != 0 || !Charable(ch)) {
285	    int len = _nc_build_wch(win, CHREF(ch));
286
287	    if (len >= -1) {
288		attr_t attr = AttrOf(ch);
289
290		/* handle EILSEQ (i.e., when len >= -1) */
291		if (len == -1 && is8bits(CharOf(ch))) {
292		    const char *s = NCURSES_SP_NAME(unctrl)
293		      (NCURSES_SP_ARGx (chtype) CharOf(ch));
294
295		    if (s[1] != '\0') {
296			int rc = OK;
297			while (*s != '\0') {
298			    rc = waddch(win, UChar(*s) | attr);
299			    if (rc != OK)
300				break;
301			    ++s;
302			}
303			return rc;
304		    }
305		}
306		if (len == -1)
307		    return waddch(win, ' ' | attr);
308	    } else {
309		return OK;
310	    }
311	}
312    });
313
314    /*
315     * Non-spacing characters are added to the current cell.
316     *
317     * Spacing characters that are wider than one column require some display
318     * adjustments.
319     */
320    if_WIDEC({
321	int len = _nc_wacs_width(CharOf(ch));
322	int i;
323	int j;
324	wchar_t *chars;
325
326	if (len == 0) {		/* non-spacing */
327	    if ((x > 0 && y >= 0)
328		|| (win->_maxx >= 0 && win->_cury >= 1)) {
329		if (x > 0 && y >= 0)
330		    chars = (win->_line[y].text[x - 1].chars);
331		else
332		    chars = (win->_line[y - 1].text[win->_maxx].chars);
333		for (i = 0; i < CCHARW_MAX; ++i) {
334		    if (chars[i] == 0) {
335			TR(TRACE_VIRTPUT,
336			   ("added non-spacing %d: %x",
337			    x, (int) CharOf(ch)));
338			chars[i] = CharOf(ch);
339			break;
340		    }
341		}
342	    }
343	    goto testwrapping;
344	} else if (len > 1) {	/* multi-column characters */
345	    /*
346	     * Check if the character will fit on the current line.  If it does
347	     * not fit, fill in the remainder of the line with blanks.  and
348	     * move to the next line.
349	     */
350	    if (len > win->_maxx + 1) {
351		TR(TRACE_VIRTPUT, ("character will not fit"));
352		return ERR;
353	    } else if (x + len > win->_maxx + 1) {
354		int count = win->_maxx + 1 - x;
355		TR(TRACE_VIRTPUT, ("fill %d remaining cells", count));
356		fill_cells(win, count);
357		if (wrap_to_next_line(win) == ERR)
358		    return ERR;
359		x = win->_curx;
360		y = win->_cury;
361		CHECK_POSITION(win, x, y);
362		line = win->_line + y;
363	    }
364	    /*
365	     * Check for cells which are orphaned by adding this character, set
366	     * those to blanks.
367	     *
368	     * FIXME: this actually could fill j-i cells, more complicated to
369	     * setup though.
370	     */
371	    for (i = 0; i < len; ++i) {
372		if (isWidecBase(win->_line[y].text[x + i])) {
373		    break;
374		} else if (isWidecExt(win->_line[y].text[x + i])) {
375		    for (j = i; x + j <= win->_maxx; ++j) {
376			if (!isWidecExt(win->_line[y].text[x + j])) {
377			    TR(TRACE_VIRTPUT, ("fill %d orphan cells", j));
378			    fill_cells(win, j);
379			    break;
380			}
381		    }
382		    break;
383		}
384	    }
385	    /*
386	     * Finally, add the cells for this character.
387	     */
388	    for (i = 0; i < len; ++i) {
389		NCURSES_CH_T value = ch;
390		SetWidecExt(value, i);
391		TR(TRACE_VIRTPUT, ("multicolumn %d:%d (%d,%d)",
392				   i + 1, len,
393				   win->_begy + y, win->_begx + x));
394		line->text[x] = value;
395		CHANGED_CELL(line, x);
396		++x;
397	    }
398	    goto testwrapping;
399	}
400    });
401
402    /*
403     * Single-column characters.
404     */
405    line->text[x++] = ch;
406    /*
407     * This label is used only for wide-characters.
408     */
409    if_WIDEC(
410  testwrapping:
411    );
412
413    TR(TRACE_VIRTPUT, ("cell (%ld, %ld..%d) = %s",
414		       (long) win->_cury, (long) win->_curx, x - 1,
415		       _tracech_t(CHREF(ch))));
416
417    if (x > win->_maxx) {
418	return wrap_to_next_line(win);
419    }
420    win->_curx = (NCURSES_SIZE_T) x;
421    return OK;
422}
423
424static NCURSES_INLINE int
425waddch_nosync(WINDOW *win, const NCURSES_CH_T ch)
426/* the workhorse function -- add a character to the given window */
427{
428    NCURSES_SIZE_T x, y;
429    chtype t = (chtype) CharOf(ch);
430#if USE_WIDEC_SUPPORT || NCURSES_SP_FUNCS || USE_REENTRANT
431    SCREEN *sp = _nc_screen_of(win);
432#endif
433    const char *s = NCURSES_SP_NAME(unctrl) (NCURSES_SP_ARGx t);
434    int tabsize = 8;
435
436    /*
437     * If we are using the alternate character set, forget about locale.
438     * Otherwise, if unctrl() returns a single-character or the locale
439     * claims the code is printable (and not also a control character),
440     * treat it that way.
441     */
442    if ((AttrOf(ch) & A_ALTCHARSET)
443	|| (
444#if USE_WIDEC_SUPPORT
445	       (sp != 0 && sp->_legacy_coding) &&
446#endif
447	       s[1] == 0
448	)
449	|| (
450	       (isprint((int) t) && !iscntrl((int) t))
451#if USE_WIDEC_SUPPORT
452	       || ((sp == 0 || !sp->_legacy_coding) &&
453		   (WINDOW_EXT(win, addch_used)
454		    || !_nc_is_charable(CharOf(ch))))
455#endif
456	)) {
457	return waddch_literal(win, ch);
458    }
459
460    /*
461     * Handle carriage control and other codes that are not printable, or are
462     * known to expand to more than one character according to unctrl().
463     */
464    x = win->_curx;
465    y = win->_cury;
466    CHECK_POSITION(win, x, y);
467
468    switch (t) {
469    case '\t':
470#if USE_REENTRANT
471	tabsize = *ptrTabsize(sp);
472#else
473	tabsize = TABSIZE;
474#endif
475	x = (NCURSES_SIZE_T) (x + (tabsize - (x % tabsize)));
476	/*
477	 * Space-fill the tab on the bottom line so that we'll get the
478	 * "correct" cursor position.
479	 */
480	if ((!win->_scroll && (y == win->_regbottom))
481	    || (x <= win->_maxx)) {
482	    NCURSES_CH_T blank = blankchar;
483	    AddAttr(blank, AttrOf(ch));
484	    while (win->_curx < x) {
485		if (waddch_literal(win, blank) == ERR)
486		    return (ERR);
487	    }
488	    break;
489	} else {
490	    wclrtoeol(win);
491	    win->_flags |= _WRAPPED;
492	    if (newline_forces_scroll(win, &y)) {
493		x = win->_maxx;
494		if (win->_scroll) {
495		    scroll(win);
496		    x = 0;
497		}
498	    } else {
499		x = 0;
500	    }
501	}
502	break;
503    case '\n':
504	wclrtoeol(win);
505	if (newline_forces_scroll(win, &y)) {
506	    if (win->_scroll)
507		scroll(win);
508	    else
509		return (ERR);
510	}
511	/* FALLTHRU */
512    case '\r':
513	x = 0;
514	win->_flags &= ~_WRAPPED;
515	break;
516    case '\b':
517	if (x == 0)
518	    return (OK);
519	x--;
520	win->_flags &= ~_WRAPPED;
521	break;
522    default:
523	while (*s) {
524	    NCURSES_CH_T sch;
525	    SetChar(sch, UChar(*s++), AttrOf(ch));
526	    if_EXT_COLORS(SetPair(sch, GetPair(ch)));
527	    if (waddch_literal(win, sch) == ERR)
528		return ERR;
529	}
530	return (OK);
531    }
532
533    win->_curx = x;
534    win->_cury = y;
535
536    return (OK);
537}
538
539NCURSES_EXPORT(int)
540_nc_waddch_nosync(WINDOW *win, const NCURSES_CH_T c)
541/* export copy of waddch_nosync() so the string-put functions can use it */
542{
543    return (waddch_nosync(win, c));
544}
545
546/*
547 * The versions below call _nc_synchook().  We wanted to avoid this in the
548 * version exported for string puts; they'll call _nc_synchook once at end
549 * of run.
550 */
551
552/* These are actual entry points */
553
554NCURSES_EXPORT(int)
555waddch(WINDOW *win, const chtype ch)
556{
557    int code = ERR;
558    NCURSES_CH_T wch;
559    SetChar2(wch, ch);
560
561    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("waddch(%p, %s)"), (void *) win,
562				      _tracechtype(ch)));
563
564    if (win && (waddch_nosync(win, wch) != ERR)) {
565	_nc_synchook(win);
566	code = OK;
567    }
568
569    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
570    return (code);
571}
572
573NCURSES_EXPORT(int)
574wechochar(WINDOW *win, const chtype ch)
575{
576    int code = ERR;
577    NCURSES_CH_T wch;
578    SetChar2(wch, ch);
579
580    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("wechochar(%p, %s)"),
581				      (void *) win,
582				      _tracechtype(ch)));
583
584    if (win && (waddch_nosync(win, wch) != ERR)) {
585	bool save_immed = win->_immed;
586	win->_immed = TRUE;
587	_nc_synchook(win);
588	win->_immed = save_immed;
589	code = OK;
590    }
591    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
592    return (code);
593}
594