1/****************************************************************************
2 * Copyright (c) 2004-2010,2011 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_add_wch.c
31**
32**	The routine wadd_wch().
33**
34*/
35
36#include <curses.priv.h>
37
38#if HAVE_WCTYPE_H
39#include <wctype.h>
40#endif
41
42MODULE_ID("$Id: lib_add_wch.c,v 1.12 2011/03/22 09:31:15 Petr.Pavlu Exp $")
43
44/* clone/adapt lib_addch.c */
45static const cchar_t blankchar = NewChar(BLANK_TEXT);
46
47/*
48 * Ugly microtweaking alert.  Everything from here to end of module is
49 * likely to be speed-critical -- profiling data sure says it is!
50 * Most of the important screen-painting functions are shells around
51 * wadd_wch().  So we make every effort to reduce function-call overhead
52 * by inlining stuff, even at the cost of making wrapped copies for
53 * export.  Also we supply some internal versions that don't call the
54 * window sync hook, for use by string-put functions.
55 */
56
57/* Return bit mask for clearing color pair number if given ch has color */
58#define COLOR_MASK(ch) (~(attr_t)((ch) & A_COLOR ? A_COLOR : 0))
59
60static NCURSES_INLINE cchar_t
61render_char(WINDOW *win, cchar_t ch)
62/* compute a rendition of the given char correct for the current context */
63{
64    attr_t a = WINDOW_ATTRS(win);
65    int pair = GetPair(ch);
66
67    if (ISBLANK(ch)
68	&& AttrOf(ch) == A_NORMAL
69	&& pair == 0) {
70	/* color/pair in attrs has precedence over bkgrnd */
71	ch = win->_nc_bkgd;
72	SetAttr(ch, a | AttrOf(win->_nc_bkgd));
73	if ((pair = GET_WINDOW_PAIR(win)) == 0)
74	    pair = GetPair(win->_nc_bkgd);
75	SetPair(ch, pair);
76    } else {
77	/* color in attrs has precedence over bkgrnd */
78	a |= AttrOf(win->_nc_bkgd) & COLOR_MASK(a);
79	/* color in ch has precedence */
80	if (pair == 0) {
81	    if ((pair = GET_WINDOW_PAIR(win)) == 0)
82		pair = GetPair(win->_nc_bkgd);
83	}
84	AddAttr(ch, (a & COLOR_MASK(AttrOf(ch))));
85	SetPair(ch, pair);
86    }
87
88    TR(TRACE_VIRTPUT,
89       ("render_char bkg %s (%d), attrs %s (%d) -> ch %s (%d)",
90	_tracech_t2(1, CHREF(win->_nc_bkgd)),
91	GetPair(win->_nc_bkgd),
92	_traceattr(WINDOW_ATTRS(win)),
93	GET_WINDOW_PAIR(win),
94	_tracech_t2(3, CHREF(ch)),
95	GetPair(ch)));
96
97    return (ch);
98}
99
100/* check if position is legal; if not, return error */
101#ifndef NDEBUG			/* treat this like an assertion */
102#define CHECK_POSITION(win, x, y) \
103	if (y > win->_maxy \
104	 || x > win->_maxx \
105	 || y < 0 \
106	 || x < 0) { \
107		TR(TRACE_VIRTPUT, ("Alert! Win=%p _curx = %d, _cury = %d " \
108				   "(_maxx = %d, _maxy = %d)", win, x, y, \
109				   win->_maxx, win->_maxy)); \
110		return(ERR); \
111	}
112#else
113#define CHECK_POSITION(win, x, y)	/* nothing */
114#endif
115
116static bool
117newline_forces_scroll(WINDOW *win, NCURSES_SIZE_T * ypos)
118{
119    bool result = FALSE;
120
121    if (*ypos >= win->_regtop && *ypos == win->_regbottom) {
122	*ypos = win->_regbottom;
123	result = TRUE;
124    } else {
125	*ypos = (NCURSES_SIZE_T) (*ypos + 1);
126    }
127    return result;
128}
129
130/*
131 * The _WRAPPED flag is useful only for telling an application that we've just
132 * wrapped the cursor.  We don't do anything with this flag except set it when
133 * wrapping, and clear it whenever we move the cursor.  If we try to wrap at
134 * the lower-right corner of a window, we cannot move the cursor (since that
135 * wouldn't be legal).  So we return an error (which is what SVr4 does).
136 * Unlike SVr4, we can successfully add a character to the lower-right corner
137 * (Solaris 2.6 does this also, however).
138 */
139static int
140wrap_to_next_line(WINDOW *win)
141{
142    win->_flags |= _WRAPPED;
143    if (newline_forces_scroll(win, &(win->_cury))) {
144	win->_curx = win->_maxx;
145	if (!win->_scroll)
146	    return (ERR);
147	scroll(win);
148    }
149    win->_curx = 0;
150    return (OK);
151}
152
153static int wadd_wch_literal(WINDOW *, cchar_t);
154/*
155 * Fill the given number of cells with blanks using the current background
156 * rendition.  This saves/restores the current x-position.
157 */
158static void
159fill_cells(WINDOW *win, int count)
160{
161    cchar_t blank = blankchar;
162    int save_x = win->_curx;
163    int save_y = win->_cury;
164
165    while (count-- > 0) {
166	if (wadd_wch_literal(win, blank) == ERR)
167	    break;
168    }
169    win->_curx = (NCURSES_SIZE_T) save_x;
170    win->_cury = (NCURSES_SIZE_T) save_y;
171}
172
173static int
174wadd_wch_literal(WINDOW *win, cchar_t ch)
175{
176    int x;
177    int y;
178    struct ldat *line;
179
180    x = win->_curx;
181    y = win->_cury;
182
183    CHECK_POSITION(win, x, y);
184
185    ch = render_char(win, ch);
186
187    line = win->_line + y;
188
189    CHANGED_CELL(line, x);
190
191    /*
192     * Non-spacing characters are added to the current cell.
193     *
194     * Spacing characters that are wider than one column require some display
195     * adjustments.
196     */
197    {
198	int len = wcwidth(CharOf(ch));
199	int i;
200	int j;
201	wchar_t *chars;
202
203	if (len == 0) {		/* non-spacing */
204	    if ((x > 0 && y >= 0)
205		|| (win->_maxx >= 0 && win->_cury >= 1)) {
206		if (x > 0 && y >= 0)
207		    chars = (win->_line[y].text[x - 1].chars);
208		else
209		    chars = (win->_line[y - 1].text[win->_maxx].chars);
210		for (i = 0; i < CCHARW_MAX; ++i) {
211		    if (chars[i] == 0) {
212			TR(TRACE_VIRTPUT,
213			   ("added non-spacing %d: %x",
214			    x, (int) CharOf(ch)));
215			chars[i] = CharOf(ch);
216			break;
217		    }
218		}
219	    }
220	    goto testwrapping;
221	} else if (len > 1) {	/* multi-column characters */
222	    /*
223	     * Check if the character will fit on the current line.  If it does
224	     * not fit, fill in the remainder of the line with blanks.  and
225	     * move to the next line.
226	     */
227	    if (len > win->_maxx + 1) {
228		TR(TRACE_VIRTPUT, ("character will not fit"));
229		return ERR;
230	    } else if (x + len > win->_maxx + 1) {
231		int count = win->_maxx + 1 - x;
232		TR(TRACE_VIRTPUT, ("fill %d remaining cells", count));
233		fill_cells(win, count);
234		if (wrap_to_next_line(win) == ERR)
235		    return ERR;
236		x = win->_curx;
237		y = win->_cury;
238		line = win->_line + y;
239	    }
240	    /*
241	     * Check for cells which are orphaned by adding this character, set
242	     * those to blanks.
243	     *
244	     * FIXME: this actually could fill j-i cells, more complicated to
245	     * setup though.
246	     */
247	    for (i = 0; i < len; ++i) {
248		if (isWidecBase(win->_line[y].text[x + i])) {
249		    break;
250		} else if (isWidecExt(win->_line[y].text[x + i])) {
251		    for (j = i; x + j <= win->_maxx; ++j) {
252			if (!isWidecExt(win->_line[y].text[x + j])) {
253			    TR(TRACE_VIRTPUT, ("fill %d orphan cells", j));
254			    fill_cells(win, j);
255			    break;
256			}
257		    }
258		    break;
259		}
260	    }
261	    /*
262	     * Finally, add the cells for this character.
263	     */
264	    for (i = 0; i < len; ++i) {
265		cchar_t value = ch;
266		SetWidecExt(value, i);
267		TR(TRACE_VIRTPUT, ("multicolumn %d:%d (%d,%d)",
268				   i + 1, len,
269				   win->_begy + y, win->_begx + x));
270		line->text[x] = value;
271		CHANGED_CELL(line, x);
272		++x;
273	    }
274	    goto testwrapping;
275	}
276    }
277
278    /*
279     * Single-column characters.
280     */
281    line->text[x++] = ch;
282    /*
283     * This label is used only for wide-characters.
284     */
285  testwrapping:
286
287    TR(TRACE_VIRTPUT, ("cell (%ld, %ld..%d) = %s",
288		       (long) win->_cury, (long) win->_curx, x - 1,
289		       _tracech_t(CHREF(ch))));
290
291    if (x > win->_maxx) {
292	return wrap_to_next_line(win);
293    }
294    win->_curx = (NCURSES_SIZE_T) x;
295    return OK;
296}
297
298static NCURSES_INLINE int
299wadd_wch_nosync(WINDOW *win, cchar_t ch)
300/* the workhorse function -- add a character to the given window */
301{
302    NCURSES_SIZE_T x, y;
303    wchar_t *s;
304    int tabsize = 8;
305#if USE_REENTRANT
306    SCREEN *sp = _nc_screen_of(win);
307#endif
308
309    /*
310     * If we are using the alternate character set, forget about locale.
311     * Otherwise, if the locale claims the code is printable, treat it that
312     * way.
313     */
314    if ((AttrOf(ch) & A_ALTCHARSET)
315	|| iswprint((wint_t) CharOf(ch)))
316	return wadd_wch_literal(win, ch);
317
318    /*
319     * Handle carriage control and other codes that are not printable, or are
320     * known to expand to more than one character according to unctrl().
321     */
322    x = win->_curx;
323    y = win->_cury;
324
325    switch (CharOf(ch)) {
326    case '\t':
327#if USE_REENTRANT
328	tabsize = *ptrTabsize(sp);
329#else
330	tabsize = TABSIZE;
331#endif
332	x = (NCURSES_SIZE_T) (x + (tabsize - (x % tabsize)));
333	/*
334	 * Space-fill the tab on the bottom line so that we'll get the
335	 * "correct" cursor position.
336	 */
337	if ((!win->_scroll && (y == win->_regbottom))
338	    || (x <= win->_maxx)) {
339	    cchar_t blank = blankchar;
340	    AddAttr(blank, AttrOf(ch));
341	    while (win->_curx < x) {
342		if (wadd_wch_literal(win, blank) == ERR)
343		    return (ERR);
344	    }
345	    break;
346	} else {
347	    wclrtoeol(win);
348	    win->_flags |= _WRAPPED;
349	    if (newline_forces_scroll(win, &y)) {
350		x = win->_maxx;
351		if (win->_scroll) {
352		    scroll(win);
353		    x = 0;
354		}
355	    } else {
356		x = 0;
357	    }
358	}
359	break;
360    case '\n':
361	wclrtoeol(win);
362	if (newline_forces_scroll(win, &y)) {
363	    if (win->_scroll)
364		scroll(win);
365	    else
366		return (ERR);
367	}
368	/* FALLTHRU */
369    case '\r':
370	x = 0;
371	win->_flags &= ~_WRAPPED;
372	break;
373    case '\b':
374	if (x == 0)
375	    return (OK);
376	x--;
377	win->_flags &= ~_WRAPPED;
378	break;
379    default:
380	if ((s = wunctrl(&ch)) != 0) {
381	    while (*s) {
382		cchar_t sch;
383		SetChar(sch, *s++, AttrOf(ch));
384		if_EXT_COLORS(SetPair(sch, GetPair(ch)));
385		if (wadd_wch_literal(win, sch) == ERR)
386		    return ERR;
387	    }
388	    return OK;
389	}
390	return ERR;
391    }
392
393    win->_curx = x;
394    win->_cury = y;
395
396    return OK;
397}
398
399/*
400 * The versions below call _nc_synchook().  We wanted to avoid this in the
401 * version exported for string puts; they'll call _nc_synchook once at end
402 * of run.
403 */
404
405/* These are actual entry points */
406
407NCURSES_EXPORT(int)
408wadd_wch(WINDOW *win, const cchar_t *wch)
409{
410    int code = ERR;
411
412    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("wadd_wch(%p, %s)"),
413				      (void *) win,
414				      _tracecchar_t(wch)));
415
416    if (win && (wadd_wch_nosync(win, *wch) != ERR)) {
417	_nc_synchook(win);
418	code = OK;
419    }
420
421    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
422    return (code);
423}
424
425NCURSES_EXPORT(int)
426wecho_wchar(WINDOW *win, const cchar_t *wch)
427{
428    int code = ERR;
429
430    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_CALLED("wechochar(%p, %s)"),
431				      (void *) win,
432				      _tracecchar_t(wch)));
433
434    if (win && (wadd_wch_nosync(win, *wch) != ERR)) {
435	bool save_immed = win->_immed;
436	win->_immed = TRUE;
437	_nc_synchook(win);
438	win->_immed = save_immed;
439	code = OK;
440    }
441    TR(TRACE_VIRTPUT | TRACE_CCALLS, (T_RETURN("%d"), code));
442    return (code);
443}
444