1 /****************************************************************************
2  * Copyright (c) 1998-2006,2007 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  *  Author: Zeyd M. Ben-Halim <zmbenhal@netcom.com> 1992,1995               *
31  *     and: Eric S. Raymond <esr@snark.thyrsus.com>                         *
32  *     and: Thomas E. Dickey                        1996-on                 *
33  ****************************************************************************/
34 
35 /* lib_color.c
36  *
37  * Handles color emulation of SYS V curses
38  */
39 
40 #include <curses.priv.h>
41 
42 #include <term.h>
43 #include <tic.h>
44 
45 MODULE_ID("$Id: lib_color.c,v 1.85 2007/04/07 17:07:28 tom Exp $")
46 
47 /*
48  * These should be screen structure members.  They need to be globals for
49  * historical reasons.  So we assign them in start_color() and also in
50  * set_term()'s screen-switching logic.
51  */
52 #if USE_REENTRANT
53 NCURSES_EXPORT(int)
54 NCURSES_PUBLIC_VAR(COLOR_PAIRS) (void)
55 {
56     return SP ? SP->_pair_count : -1;
57 }
58 NCURSES_EXPORT(int)
59 NCURSES_PUBLIC_VAR(COLORS) (void)
60 {
61     return SP ? SP->_color_count : -1;
62 }
63 #else
64 NCURSES_EXPORT_VAR(int) COLOR_PAIRS = 0;
65 NCURSES_EXPORT_VAR(int) COLORS = 0;
66 #endif
67 
68 #define DATA(r,g,b) {r,g,b, 0,0,0, 0}
69 
70 #define TYPE_CALLOC(type,elts) typeCalloc(type, (unsigned)(elts))
71 
72 #define MAX_PALETTE	8
73 
74 #define OkColorHi(n)	(((n) < COLORS) && ((n) < max_colors))
75 #define InPalette(n)	((n) >= 0 && (n) < MAX_PALETTE)
76 
77 /*
78  * Given a RGB range of 0..1000, we'll normally set the individual values
79  * to about 2/3 of the maximum, leaving full-range for bold/bright colors.
80  */
81 #define RGB_ON  680
82 #define RGB_OFF 0
83 /* *INDENT-OFF* */
84 static const color_t cga_palette[] =
85 {
86     /*  R               G               B */
87     DATA(RGB_OFF,	RGB_OFF,	RGB_OFF),	/* COLOR_BLACK */
88     DATA(RGB_ON,	RGB_OFF,	RGB_OFF),	/* COLOR_RED */
89     DATA(RGB_OFF,	RGB_ON,		RGB_OFF),	/* COLOR_GREEN */
90     DATA(RGB_ON,	RGB_ON,		RGB_OFF),	/* COLOR_YELLOW */
91     DATA(RGB_OFF,	RGB_OFF,	RGB_ON),	/* COLOR_BLUE */
92     DATA(RGB_ON,	RGB_OFF,	RGB_ON),	/* COLOR_MAGENTA */
93     DATA(RGB_OFF,	RGB_ON,		RGB_ON),	/* COLOR_CYAN */
94     DATA(RGB_ON,	RGB_ON,		RGB_ON),	/* COLOR_WHITE */
95 };
96 
97 static const color_t hls_palette[] =
98 {
99     /*  	H       L       S */
100     DATA(	0,	0,	0),		/* COLOR_BLACK */
101     DATA(	120,	50,	100),		/* COLOR_RED */
102     DATA(	240,	50,	100),		/* COLOR_GREEN */
103     DATA(	180,	50,	100),		/* COLOR_YELLOW */
104     DATA(	330,	50,	100),		/* COLOR_BLUE */
105     DATA(	60,	50,	100),		/* COLOR_MAGENTA */
106     DATA(	300,	50,	100),		/* COLOR_CYAN */
107     DATA(	0,	50,	100),		/* COLOR_WHITE */
108 };
109 /* *INDENT-ON* */
110 
111 #if NCURSES_EXT_FUNCS
112 /*
113  * These are called from _nc_do_color(), which in turn is called from
114  * vidattr - so we have to assume that SP may be null.
115  */
116 static int
117 default_fg(void)
118 {
119     return (SP != 0) ? SP->_default_fg : COLOR_WHITE;
120 }
121 
122 static int
123 default_bg(void)
124 {
125     return SP != 0 ? SP->_default_bg : COLOR_BLACK;
126 }
127 #else
128 #define default_fg() COLOR_WHITE
129 #define default_bg() COLOR_BLACK
130 #endif
131 
132 /*
133  * SVr4 curses is known to interchange color codes (1,4) and (3,6), possibly
134  * to maintain compatibility with a pre-ANSI scheme.  The same scheme is
135  * also used in the FreeBSD syscons.
136  */
137 static int
138 toggled_colors(int c)
139 {
140     if (c < 16) {
141 	static const int table[] =
142 	{0, 4, 2, 6, 1, 5, 3, 7,
143 	 8, 12, 10, 14, 9, 13, 11, 15};
144 	c = table[c];
145     }
146     return c;
147 }
148 
149 static void
150 set_background_color(int bg, int (*outc) (int))
151 {
152     if (set_a_background) {
153 	TPUTS_TRACE("set_a_background");
154 	tputs(TPARM_1(set_a_background, bg), 1, outc);
155     } else {
156 	TPUTS_TRACE("set_background");
157 	tputs(TPARM_1(set_background, toggled_colors(bg)), 1, outc);
158     }
159 }
160 
161 static void
162 set_foreground_color(int fg, int (*outc) (int))
163 {
164     if (set_a_foreground) {
165 	TPUTS_TRACE("set_a_foreground");
166 	tputs(TPARM_1(set_a_foreground, fg), 1, outc);
167     } else {
168 	TPUTS_TRACE("set_foreground");
169 	tputs(TPARM_1(set_foreground, toggled_colors(fg)), 1, outc);
170     }
171 }
172 
173 static void
174 init_color_table(void)
175 {
176     const color_t *tp;
177     int n;
178 
179     tp = (hue_lightness_saturation) ? hls_palette : cga_palette;
180     for (n = 0; n < COLORS; n++) {
181 	if (InPalette(n)) {
182 	    SP->_color_table[n] = tp[n];
183 	} else {
184 	    SP->_color_table[n] = tp[n % MAX_PALETTE];
185 	    if (hue_lightness_saturation) {
186 		SP->_color_table[n].green = 100;
187 	    } else {
188 		if (SP->_color_table[n].red)
189 		    SP->_color_table[n].red = 1000;
190 		if (SP->_color_table[n].green)
191 		    SP->_color_table[n].green = 1000;
192 		if (SP->_color_table[n].blue)
193 		    SP->_color_table[n].blue = 1000;
194 	    }
195 	}
196     }
197 }
198 
199 /*
200  * Reset the color pair, e.g., to whatever color pair 0 is.
201  */
202 static bool
203 reset_color_pair(void)
204 {
205     bool result = FALSE;
206 
207     if (orig_pair != 0) {
208 	TPUTS_TRACE("orig_pair");
209 	putp(orig_pair);
210 	result = TRUE;
211     }
212     return result;
213 }
214 
215 /*
216  * Reset color pairs and definitions.  Actually we do both more to accommodate
217  * badly-written terminal descriptions than for the relatively rare case where
218  * someone has changed the color definitions.
219  */
220 bool
221 _nc_reset_colors(void)
222 {
223     int result = FALSE;
224 
225     T((T_CALLED("_nc_reset_colors()")));
226     if (SP->_color_defs > 0)
227 	SP->_color_defs = -(SP->_color_defs);
228 
229     if (reset_color_pair())
230 	result = TRUE;
231     if (orig_colors != 0) {
232 	TPUTS_TRACE("orig_colors");
233 	putp(orig_colors);
234 	result = TRUE;
235     }
236     returnBool(result);
237 }
238 
239 NCURSES_EXPORT(int)
240 start_color(void)
241 {
242     int result = ERR;
243 
244     T((T_CALLED("start_color()")));
245 
246     if (SP == 0) {
247 	result = ERR;
248     } else if (SP->_coloron) {
249 	result = OK;
250     } else {
251 
252 	if (reset_color_pair() != TRUE) {
253 	    set_foreground_color(default_fg(), _nc_outch);
254 	    set_background_color(default_bg(), _nc_outch);
255 	}
256 
257 	if (max_pairs > 0 && max_colors > 0) {
258 	    SP->_pair_count = max_pairs;
259 	    SP->_color_count = max_colors;
260 #if !USE_REENTRANT
261 	    COLOR_PAIRS = max_pairs;
262 	    COLORS = max_colors;
263 #endif
264 
265 	    if ((SP->_color_pairs = TYPE_CALLOC(colorpair_t,
266 						max_pairs)) != 0) {
267 		if ((SP->_color_table = TYPE_CALLOC(color_t,
268 						    max_colors)) != 0) {
269 		    SP->_color_pairs[0] = PAIR_OF(default_fg(), default_bg());
270 		    init_color_table();
271 
272 		    T(("started color: COLORS = %d, COLOR_PAIRS = %d",
273 		       COLORS, COLOR_PAIRS));
274 
275 		    SP->_coloron = 1;
276 		    result = OK;
277 		} else if (SP->_color_pairs != 0) {
278 		    FreeAndNull(SP->_color_pairs);
279 		}
280 	    }
281 	} else {
282 	    result = OK;
283 	}
284     }
285     returnCode(result);
286 }
287 
288 /* This function was originally written by Daniel Weaver <danw@znyx.com> */
289 static void
290 rgb2hls(short r, short g, short b, short *h, short *l, short *s)
291 /* convert RGB to HLS system */
292 {
293     short min, max, t;
294 
295     if ((min = g < r ? g : r) > b)
296 	min = b;
297     if ((max = g > r ? g : r) < b)
298 	max = b;
299 
300     /* calculate lightness */
301     *l = (min + max) / 20;
302 
303     if (min == max) {		/* black, white and all shades of gray */
304 	*h = 0;
305 	*s = 0;
306 	return;
307     }
308 
309     /* calculate saturation */
310     if (*l < 50)
311 	*s = ((max - min) * 100) / (max + min);
312     else
313 	*s = ((max - min) * 100) / (2000 - max - min);
314 
315     /* calculate hue */
316     if (r == max)
317 	t = 120 + ((g - b) * 60) / (max - min);
318     else if (g == max)
319 	t = 240 + ((b - r) * 60) / (max - min);
320     else
321 	t = 360 + ((r - g) * 60) / (max - min);
322 
323     *h = t % 360;
324 }
325 
326 /*
327  * Extension (1997/1/18) - Allow negative f/b values to set default color
328  * values.
329  */
330 NCURSES_EXPORT(int)
331 init_pair(short pair, short f, short b)
332 {
333     colorpair_t result;
334 
335     T((T_CALLED("init_pair(%d,%d,%d)"), pair, f, b));
336 
337     if ((pair < 0) || (pair >= COLOR_PAIRS) || SP == 0 || !SP->_coloron)
338 	returnCode(ERR);
339 #if NCURSES_EXT_FUNCS
340     if (SP->_default_color) {
341 	if (f < 0)
342 	    f = COLOR_DEFAULT;
343 	if (b < 0)
344 	    b = COLOR_DEFAULT;
345 	if (!OkColorHi(f) && !isDefaultColor(f))
346 	    returnCode(ERR);
347 	if (!OkColorHi(b) && !isDefaultColor(b))
348 	    returnCode(ERR);
349     } else
350 #endif
351     {
352 	if ((f < 0) || !OkColorHi(f)
353 	    || (b < 0) || !OkColorHi(b)
354 	    || (pair < 1))
355 	    returnCode(ERR);
356     }
357 
358     /*
359      * When a pair's content is changed, replace its colors (if pair was
360      * initialized before a screen update is performed replacing original
361      * pair colors with the new ones).
362      */
363     result = PAIR_OF(f, b);
364     if (SP->_color_pairs[pair] != 0
365 	&& SP->_color_pairs[pair] != result) {
366 	int y, x;
367 
368 	for (y = 0; y <= curscr->_maxy; y++) {
369 	    struct ldat *ptr = &(curscr->_line[y]);
370 	    bool changed = FALSE;
371 	    for (x = 0; x <= curscr->_maxx; x++) {
372 		if (GetPair(ptr->text[x]) == pair) {
373 		    /* Set the old cell to zero to ensure it will be
374 		       updated on the next doupdate() */
375 		    SetChar(ptr->text[x], 0, 0);
376 		    CHANGED_CELL(ptr, x);
377 		    changed = TRUE;
378 		}
379 	    }
380 	    if (changed)
381 		_nc_make_oldhash(y);
382 	}
383     }
384     SP->_color_pairs[pair] = result;
385     if (GET_SCREEN_PAIR(SP) == pair)
386 	SET_SCREEN_PAIR(SP, (chtype) (~0));	/* force attribute update */
387 
388     if (initialize_pair && InPalette(f) && InPalette(b)) {
389 	const color_t *tp = hue_lightness_saturation ? hls_palette : cga_palette;
390 
391 	TR(TRACE_ATTRS,
392 	   ("initializing pair: pair = %d, fg=(%d,%d,%d), bg=(%d,%d,%d)",
393 	    pair,
394 	    tp[f].red, tp[f].green, tp[f].blue,
395 	    tp[b].red, tp[b].green, tp[b].blue));
396 
397 	TPUTS_TRACE("initialize_pair");
398 	putp(TPARM_7(initialize_pair,
399 		     pair,
400 		     tp[f].red, tp[f].green, tp[f].blue,
401 		     tp[b].red, tp[b].green, tp[b].blue));
402     }
403 
404     returnCode(OK);
405 }
406 
407 #define okRGB(n) ((n) >= 0 && (n) <= 1000)
408 
409 NCURSES_EXPORT(int)
410 init_color(short color, short r, short g, short b)
411 {
412     int result = ERR;
413 
414     T((T_CALLED("init_color(%d,%d,%d,%d)"), color, r, g, b));
415 
416     if (initialize_color != NULL
417 	&& SP != 0
418 	&& SP->_coloron
419 	&& (color >= 0 && OkColorHi(color))
420 	&& (okRGB(r) && okRGB(g) && okRGB(b))) {
421 
422 	SP->_color_table[color].init = 1;
423 	SP->_color_table[color].r = r;
424 	SP->_color_table[color].g = g;
425 	SP->_color_table[color].b = b;
426 
427 	if (hue_lightness_saturation) {
428 	    rgb2hls(r, g, b,
429 		    &SP->_color_table[color].red,
430 		    &SP->_color_table[color].green,
431 		    &SP->_color_table[color].blue);
432 	} else {
433 	    SP->_color_table[color].red = r;
434 	    SP->_color_table[color].green = g;
435 	    SP->_color_table[color].blue = b;
436 	}
437 
438 	TPUTS_TRACE("initialize_color");
439 	putp(TPARM_4(initialize_color, color, r, g, b));
440 	SP->_color_defs = max(color + 1, SP->_color_defs);
441 	result = OK;
442     }
443     returnCode(result);
444 }
445 
446 NCURSES_EXPORT(bool)
447 can_change_color(void)
448 {
449     T((T_CALLED("can_change_color()")));
450     returnCode((can_change != 0) ? TRUE : FALSE);
451 }
452 
453 NCURSES_EXPORT(bool)
454 has_colors(void)
455 {
456     T((T_CALLED("has_colors()")));
457     returnCode((VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
458 		&& (((set_foreground != NULL)
459 		     && (set_background != NULL))
460 		    || ((set_a_foreground != NULL)
461 			&& (set_a_background != NULL))
462 		    || set_color_pair)) ? TRUE : FALSE);
463 }
464 
465 NCURSES_EXPORT(int)
466 color_content(short color, short *r, short *g, short *b)
467 {
468     int result;
469 
470     T((T_CALLED("color_content(%d,%p,%p,%p)"), color, r, g, b));
471     if (color < 0 || !OkColorHi(color) || SP == 0 || !SP->_coloron) {
472 	result = ERR;
473     } else {
474 	NCURSES_COLOR_T c_r = SP->_color_table[color].red;
475 	NCURSES_COLOR_T c_g = SP->_color_table[color].green;
476 	NCURSES_COLOR_T c_b = SP->_color_table[color].blue;
477 
478 	if (r)
479 	    *r = c_r;
480 	if (g)
481 	    *g = c_g;
482 	if (b)
483 	    *b = c_b;
484 
485 	TR(TRACE_ATTRS, ("...color_content(%d,%d,%d,%d)",
486 			 color, c_r, c_g, c_b));
487 	result = OK;
488     }
489     returnCode(result);
490 }
491 
492 NCURSES_EXPORT(int)
493 pair_content(short pair, short *f, short *b)
494 {
495     int result;
496 
497     T((T_CALLED("pair_content(%d,%p,%p)"), pair, f, b));
498 
499     if ((pair < 0) || (pair >= COLOR_PAIRS) || SP == 0 || !SP->_coloron) {
500 	result = ERR;
501     } else {
502 	NCURSES_COLOR_T fg = ((SP->_color_pairs[pair] >> C_SHIFT) & C_MASK);
503 	NCURSES_COLOR_T bg = (SP->_color_pairs[pair] & C_MASK);
504 
505 #if NCURSES_EXT_FUNCS
506 	if (fg == COLOR_DEFAULT)
507 	    fg = -1;
508 	if (bg == COLOR_DEFAULT)
509 	    bg = -1;
510 #endif
511 
512 	if (f)
513 	    *f = fg;
514 	if (b)
515 	    *b = bg;
516 
517 	TR(TRACE_ATTRS, ("...pair_content(%d,%d,%d)", pair, fg, bg));
518 	result = OK;
519     }
520     returnCode(result);
521 }
522 
523 NCURSES_EXPORT(void)
524 _nc_do_color(short old_pair, short pair, bool reverse, int (*outc) (int))
525 {
526     NCURSES_COLOR_T fg = COLOR_DEFAULT;
527     NCURSES_COLOR_T bg = COLOR_DEFAULT;
528     NCURSES_COLOR_T old_fg, old_bg;
529 
530     if (pair < 0 || pair >= COLOR_PAIRS) {
531 	return;
532     } else if (pair != 0) {
533 	if (set_color_pair) {
534 	    TPUTS_TRACE("set_color_pair");
535 	    tputs(TPARM_1(set_color_pair, pair), 1, outc);
536 	    return;
537 	} else if (SP != 0) {
538 	    pair_content((short) pair, &fg, &bg);
539 	}
540     }
541 
542     if (old_pair >= 0
543 	&& SP != 0
544 	&& pair_content(old_pair, &old_fg, &old_bg) != ERR) {
545 	if ((isDefaultColor(fg) && !isDefaultColor(old_fg))
546 	    || (isDefaultColor(bg) && !isDefaultColor(old_bg))) {
547 #if NCURSES_EXT_FUNCS
548 	    /*
549 	     * A minor optimization - but extension.  If "AX" is specified in
550 	     * the terminal description, treat it as screen's indicator of ECMA
551 	     * SGR 39 and SGR 49, and assume the two sequences are independent.
552 	     */
553 	    if (SP->_has_sgr_39_49
554 		&& isDefaultColor(old_bg)
555 		&& !isDefaultColor(old_fg)) {
556 		tputs("\033[39m", 1, outc);
557 	    } else if (SP->_has_sgr_39_49
558 		       && isDefaultColor(old_fg)
559 		       && !isDefaultColor(old_bg)) {
560 		tputs("\033[49m", 1, outc);
561 	    } else
562 #endif
563 		reset_color_pair();
564 	}
565     } else {
566 	reset_color_pair();
567 	if (old_pair < 0)
568 	    return;
569     }
570 
571 #if NCURSES_EXT_FUNCS
572     if (isDefaultColor(fg))
573 	fg = default_fg();
574     if (isDefaultColor(bg))
575 	bg = default_bg();
576 #endif
577 
578     if (reverse) {
579 	NCURSES_COLOR_T xx = fg;
580 	fg = bg;
581 	bg = xx;
582     }
583 
584     TR(TRACE_ATTRS, ("setting colors: pair = %d, fg = %d, bg = %d", pair,
585 		     fg, bg));
586 
587     if (!isDefaultColor(fg)) {
588 	set_foreground_color(fg, outc);
589     }
590     if (!isDefaultColor(bg)) {
591 	set_background_color(bg, outc);
592     }
593 }
594