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