]> ncurses.scripts.mit.edu Git - ncurses.git/blob - ncurses/base/lib_color.c
ncurses 5.7 - patch 20090124
[ncurses.git] / ncurses / base / lib_color.c
1 /****************************************************************************
2  * Copyright (c) 1998-2007,2009 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.87 2009/01/25 00:25:31 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 /*
112  * Ensure that we use color pairs only when colors have been started, and also
113  * that the index is within the limits of the table which we allocated.
114  */
115 #define ValidPair(pair) \
116     ((SP != 0) && (pair >= 0) && (pair < SP->_pair_limit) && SP->_coloron)
117
118 #if NCURSES_EXT_FUNCS
119 /*
120  * These are called from _nc_do_color(), which in turn is called from
121  * vidattr - so we have to assume that SP may be null.
122  */
123 static int
124 default_fg(void)
125 {
126     return (SP != 0) ? SP->_default_fg : COLOR_WHITE;
127 }
128
129 static int
130 default_bg(void)
131 {
132     return SP != 0 ? SP->_default_bg : COLOR_BLACK;
133 }
134 #else
135 #define default_fg() COLOR_WHITE
136 #define default_bg() COLOR_BLACK
137 #endif
138
139 /*
140  * SVr4 curses is known to interchange color codes (1,4) and (3,6), possibly
141  * to maintain compatibility with a pre-ANSI scheme.  The same scheme is
142  * also used in the FreeBSD syscons.
143  */
144 static int
145 toggled_colors(int c)
146 {
147     if (c < 16) {
148         static const int table[] =
149         {0, 4, 2, 6, 1, 5, 3, 7,
150          8, 12, 10, 14, 9, 13, 11, 15};
151         c = table[c];
152     }
153     return c;
154 }
155
156 static void
157 set_background_color(int bg, int (*outc) (int))
158 {
159     if (set_a_background) {
160         TPUTS_TRACE("set_a_background");
161         tputs(TPARM_1(set_a_background, bg), 1, outc);
162     } else {
163         TPUTS_TRACE("set_background");
164         tputs(TPARM_1(set_background, toggled_colors(bg)), 1, outc);
165     }
166 }
167
168 static void
169 set_foreground_color(int fg, int (*outc) (int))
170 {
171     if (set_a_foreground) {
172         TPUTS_TRACE("set_a_foreground");
173         tputs(TPARM_1(set_a_foreground, fg), 1, outc);
174     } else {
175         TPUTS_TRACE("set_foreground");
176         tputs(TPARM_1(set_foreground, toggled_colors(fg)), 1, outc);
177     }
178 }
179
180 static void
181 init_color_table(void)
182 {
183     const color_t *tp;
184     int n;
185
186     tp = (hue_lightness_saturation) ? hls_palette : cga_palette;
187     for (n = 0; n < COLORS; n++) {
188         if (InPalette(n)) {
189             SP->_color_table[n] = tp[n];
190         } else {
191             SP->_color_table[n] = tp[n % MAX_PALETTE];
192             if (hue_lightness_saturation) {
193                 SP->_color_table[n].green = 100;
194             } else {
195                 if (SP->_color_table[n].red)
196                     SP->_color_table[n].red = 1000;
197                 if (SP->_color_table[n].green)
198                     SP->_color_table[n].green = 1000;
199                 if (SP->_color_table[n].blue)
200                     SP->_color_table[n].blue = 1000;
201             }
202         }
203     }
204 }
205
206 /*
207  * Reset the color pair, e.g., to whatever color pair 0 is.
208  */
209 static bool
210 reset_color_pair(void)
211 {
212     bool result = FALSE;
213
214     if (orig_pair != 0) {
215         TPUTS_TRACE("orig_pair");
216         putp(orig_pair);
217         result = TRUE;
218     }
219     return result;
220 }
221
222 /*
223  * Reset color pairs and definitions.  Actually we do both more to accommodate
224  * badly-written terminal descriptions than for the relatively rare case where
225  * someone has changed the color definitions.
226  */
227 bool
228 _nc_reset_colors(void)
229 {
230     int result = FALSE;
231
232     T((T_CALLED("_nc_reset_colors()")));
233     if (SP->_color_defs > 0)
234         SP->_color_defs = -(SP->_color_defs);
235
236     if (reset_color_pair())
237         result = TRUE;
238     if (orig_colors != 0) {
239         TPUTS_TRACE("orig_colors");
240         putp(orig_colors);
241         result = TRUE;
242     }
243     returnBool(result);
244 }
245
246 NCURSES_EXPORT(int)
247 start_color(void)
248 {
249     int result = ERR;
250
251     T((T_CALLED("start_color()")));
252
253     if (SP == 0) {
254         result = ERR;
255     } else if (SP->_coloron) {
256         result = OK;
257     } else {
258
259         if (reset_color_pair() != TRUE) {
260             set_foreground_color(default_fg(), _nc_outch);
261             set_background_color(default_bg(), _nc_outch);
262         }
263
264         if (max_pairs > 0 && max_colors > 0) {
265             SP->_pair_limit = max_pairs;
266
267 #if NCURSES_EXT_FUNCS
268             /*
269              * If using default colors, allocate extra space in table to
270              * allow for default-color as a component of a color-pair.
271              */
272             SP->_pair_limit += (1 + (2 * max_colors));
273 #endif
274             SP->_pair_count = max_pairs;
275             SP->_color_count = max_colors;
276 #if !USE_REENTRANT
277             COLOR_PAIRS = max_pairs;
278             COLORS = max_colors;
279 #endif
280
281             if ((SP->_color_pairs = TYPE_CALLOC(colorpair_t,
282                                                 SP->_pair_limit)) != 0) {
283                 if ((SP->_color_table = TYPE_CALLOC(color_t,
284                                                     max_colors)) != 0) {
285                     SP->_color_pairs[0] = PAIR_OF(default_fg(), default_bg());
286                     init_color_table();
287
288                     T(("started color: COLORS = %d, COLOR_PAIRS = %d",
289                        COLORS, COLOR_PAIRS));
290
291                     SP->_coloron = 1;
292                     result = OK;
293                 } else if (SP->_color_pairs != 0) {
294                     FreeAndNull(SP->_color_pairs);
295                 }
296             }
297         } else {
298             result = OK;
299         }
300     }
301     returnCode(result);
302 }
303
304 /* This function was originally written by Daniel Weaver <danw@znyx.com> */
305 static void
306 rgb2hls(short r, short g, short b, short *h, short *l, short *s)
307 /* convert RGB to HLS system */
308 {
309     short min, max, t;
310
311     if ((min = g < r ? g : r) > b)
312         min = b;
313     if ((max = g > r ? g : r) < b)
314         max = b;
315
316     /* calculate lightness */
317     *l = (min + max) / 20;
318
319     if (min == max) {           /* black, white and all shades of gray */
320         *h = 0;
321         *s = 0;
322         return;
323     }
324
325     /* calculate saturation */
326     if (*l < 50)
327         *s = ((max - min) * 100) / (max + min);
328     else
329         *s = ((max - min) * 100) / (2000 - max - min);
330
331     /* calculate hue */
332     if (r == max)
333         t = 120 + ((g - b) * 60) / (max - min);
334     else if (g == max)
335         t = 240 + ((b - r) * 60) / (max - min);
336     else
337         t = 360 + ((r - g) * 60) / (max - min);
338
339     *h = t % 360;
340 }
341
342 /*
343  * Extension (1997/1/18) - Allow negative f/b values to set default color
344  * values.
345  */
346 NCURSES_EXPORT(int)
347 init_pair(short pair, short f, short b)
348 {
349     colorpair_t result;
350     colorpair_t previous;
351
352     T((T_CALLED("init_pair(%d,%d,%d)"), pair, f, b));
353
354     if (!ValidPair(pair))
355         returnCode(ERR);
356
357     previous = SP->_color_pairs[pair];
358 #if NCURSES_EXT_FUNCS
359     if (SP->_default_color) {
360         bool isDefault = FALSE;
361         bool wasDefault = FALSE;
362         int default_pairs = SP->_default_pairs;
363
364         /*
365          * Map caller's color number, e.g., -1, 0, 1, .., 7, etc., into
366          * internal unsigned values which we will store in the _color_pairs[]
367          * table.
368          */
369         if (isDefaultColor(f)) {
370             f = COLOR_DEFAULT;
371             isDefault = TRUE;
372         } else if (!OkColorHi(f)) {
373             returnCode(ERR);
374         }
375
376         if (isDefaultColor(b)) {
377             b = COLOR_DEFAULT;
378             isDefault = TRUE;
379         } else if (!OkColorHi(b)) {
380             returnCode(ERR);
381         }
382
383         /*
384          * Check if the table entry that we are going to init/update used
385          * default colors.
386          */
387         if ((FORE_OF(previous) == COLOR_DEFAULT)
388             || (BACK_OF(previous) == COLOR_DEFAULT))
389             wasDefault = TRUE;
390
391         /*
392          * Keep track of the number of entries in the color pair table which
393          * used a default color.
394          */
395         if (isDefault && !wasDefault) {
396             ++default_pairs;
397         } else if (wasDefault && !isDefault) {
398             --default_pairs;
399         }
400
401         /*
402          * As an extension, ncurses allows the pair number to exceed the
403          * terminal's color_pairs value for pairs using a default color.
404          *
405          * Note that updating a pair which used a default color with one
406          * that does not will decrement the count - and possibly interfere
407          * with sequentially adding new pairs.
408          */
409         if (pair > (SP->_pair_count + default_pairs)) {
410             returnCode(ERR);
411         }
412         SP->_default_pairs = default_pairs;
413     } else
414 #endif
415     {
416         if ((f < 0) || !OkColorHi(f)
417             || (b < 0) || !OkColorHi(b)
418             || (pair < 1))
419             returnCode(ERR);
420     }
421
422     /*
423      * When a pair's content is changed, replace its colors (if pair was
424      * initialized before a screen update is performed replacing original
425      * pair colors with the new ones).
426      */
427     result = PAIR_OF(f, b);
428     if (previous != 0
429         && previous != result) {
430         int y, x;
431
432         for (y = 0; y <= curscr->_maxy; y++) {
433             struct ldat *ptr = &(curscr->_line[y]);
434             bool changed = FALSE;
435             for (x = 0; x <= curscr->_maxx; x++) {
436                 if (GetPair(ptr->text[x]) == pair) {
437                     /* Set the old cell to zero to ensure it will be
438                        updated on the next doupdate() */
439                     SetChar(ptr->text[x], 0, 0);
440                     CHANGED_CELL(ptr, x);
441                     changed = TRUE;
442                 }
443             }
444             if (changed)
445                 _nc_make_oldhash(y);
446         }
447     }
448     SP->_color_pairs[pair] = result;
449     if (GET_SCREEN_PAIR(SP) == pair)
450         SET_SCREEN_PAIR(SP, (chtype) (~0));     /* force attribute update */
451
452     if (initialize_pair && InPalette(f) && InPalette(b)) {
453         const color_t *tp = hue_lightness_saturation ? hls_palette : cga_palette;
454
455         TR(TRACE_ATTRS,
456            ("initializing pair: pair = %d, fg=(%d,%d,%d), bg=(%d,%d,%d)",
457             pair,
458             tp[f].red, tp[f].green, tp[f].blue,
459             tp[b].red, tp[b].green, tp[b].blue));
460
461         TPUTS_TRACE("initialize_pair");
462         putp(TPARM_7(initialize_pair,
463                      pair,
464                      tp[f].red, tp[f].green, tp[f].blue,
465                      tp[b].red, tp[b].green, tp[b].blue));
466     }
467
468     returnCode(OK);
469 }
470
471 #define okRGB(n) ((n) >= 0 && (n) <= 1000)
472
473 NCURSES_EXPORT(int)
474 init_color(short color, short r, short g, short b)
475 {
476     int result = ERR;
477
478     T((T_CALLED("init_color(%d,%d,%d,%d)"), color, r, g, b));
479
480     if (initialize_color != NULL
481         && SP != 0
482         && SP->_coloron
483         && (color >= 0 && OkColorHi(color))
484         && (okRGB(r) && okRGB(g) && okRGB(b))) {
485
486         SP->_color_table[color].init = 1;
487         SP->_color_table[color].r = r;
488         SP->_color_table[color].g = g;
489         SP->_color_table[color].b = b;
490
491         if (hue_lightness_saturation) {
492             rgb2hls(r, g, b,
493                     &SP->_color_table[color].red,
494                     &SP->_color_table[color].green,
495                     &SP->_color_table[color].blue);
496         } else {
497             SP->_color_table[color].red = r;
498             SP->_color_table[color].green = g;
499             SP->_color_table[color].blue = b;
500         }
501
502         TPUTS_TRACE("initialize_color");
503         putp(TPARM_4(initialize_color, color, r, g, b));
504         SP->_color_defs = max(color + 1, SP->_color_defs);
505         result = OK;
506     }
507     returnCode(result);
508 }
509
510 NCURSES_EXPORT(bool)
511 can_change_color(void)
512 {
513     T((T_CALLED("can_change_color()")));
514     returnCode((can_change != 0) ? TRUE : FALSE);
515 }
516
517 NCURSES_EXPORT(bool)
518 has_colors(void)
519 {
520     T((T_CALLED("has_colors()")));
521     returnCode((VALID_NUMERIC(max_colors) && VALID_NUMERIC(max_pairs)
522                 && (((set_foreground != NULL)
523                      && (set_background != NULL))
524                     || ((set_a_foreground != NULL)
525                         && (set_a_background != NULL))
526                     || set_color_pair)) ? TRUE : FALSE);
527 }
528
529 NCURSES_EXPORT(int)
530 color_content(short color, short *r, short *g, short *b)
531 {
532     int result;
533
534     T((T_CALLED("color_content(%d,%p,%p,%p)"), color, r, g, b));
535     if (color < 0 || !OkColorHi(color) || SP == 0 || !SP->_coloron) {
536         result = ERR;
537     } else {
538         NCURSES_COLOR_T c_r = SP->_color_table[color].red;
539         NCURSES_COLOR_T c_g = SP->_color_table[color].green;
540         NCURSES_COLOR_T c_b = SP->_color_table[color].blue;
541
542         if (r)
543             *r = c_r;
544         if (g)
545             *g = c_g;
546         if (b)
547             *b = c_b;
548
549         TR(TRACE_ATTRS, ("...color_content(%d,%d,%d,%d)",
550                          color, c_r, c_g, c_b));
551         result = OK;
552     }
553     returnCode(result);
554 }
555
556 NCURSES_EXPORT(int)
557 pair_content(short pair, short *f, short *b)
558 {
559     int result;
560
561     T((T_CALLED("pair_content(%d,%p,%p)"), pair, f, b));
562
563     if (!ValidPair(pair)) {
564         result = ERR;
565     } else {
566         NCURSES_COLOR_T fg = FORE_OF(SP->_color_pairs[pair]);
567         NCURSES_COLOR_T bg = BACK_OF(SP->_color_pairs[pair]);
568
569 #if NCURSES_EXT_FUNCS
570         if (fg == COLOR_DEFAULT)
571             fg = -1;
572         if (bg == COLOR_DEFAULT)
573             bg = -1;
574 #endif
575
576         if (f)
577             *f = fg;
578         if (b)
579             *b = bg;
580
581         TR(TRACE_ATTRS, ("...pair_content(%d,%d,%d)", pair, fg, bg));
582         result = OK;
583     }
584     returnCode(result);
585 }
586
587 NCURSES_EXPORT(void)
588 _nc_do_color(short old_pair, short pair, bool reverse, int (*outc) (int))
589 {
590     NCURSES_COLOR_T fg = COLOR_DEFAULT;
591     NCURSES_COLOR_T bg = COLOR_DEFAULT;
592     NCURSES_COLOR_T old_fg, old_bg;
593
594     if (!ValidPair(pair)) {
595         return;
596     } else if (pair != 0) {
597         if (set_color_pair) {
598             TPUTS_TRACE("set_color_pair");
599             tputs(TPARM_1(set_color_pair, pair), 1, outc);
600             return;
601         } else if (SP != 0) {
602             pair_content((short) pair, &fg, &bg);
603         }
604     }
605
606     if (old_pair >= 0
607         && SP != 0
608         && pair_content(old_pair, &old_fg, &old_bg) != ERR) {
609         if ((isDefaultColor(fg) && !isDefaultColor(old_fg))
610             || (isDefaultColor(bg) && !isDefaultColor(old_bg))) {
611 #if NCURSES_EXT_FUNCS
612             /*
613              * A minor optimization - but extension.  If "AX" is specified in
614              * the terminal description, treat it as screen's indicator of ECMA
615              * SGR 39 and SGR 49, and assume the two sequences are independent.
616              */
617             if (SP->_has_sgr_39_49
618                 && isDefaultColor(old_bg)
619                 && !isDefaultColor(old_fg)) {
620                 tputs("\033[39m", 1, outc);
621             } else if (SP->_has_sgr_39_49
622                        && isDefaultColor(old_fg)
623                        && !isDefaultColor(old_bg)) {
624                 tputs("\033[49m", 1, outc);
625             } else
626 #endif
627                 reset_color_pair();
628         }
629     } else {
630         reset_color_pair();
631         if (old_pair < 0)
632             return;
633     }
634
635 #if NCURSES_EXT_FUNCS
636     if (isDefaultColor(fg))
637         fg = default_fg();
638     if (isDefaultColor(bg))
639         bg = default_bg();
640 #endif
641
642     if (reverse) {
643         NCURSES_COLOR_T xx = fg;
644         fg = bg;
645         bg = xx;
646     }
647
648     TR(TRACE_ATTRS, ("setting colors: pair = %d, fg = %d, bg = %d", pair,
649                      fg, bg));
650
651     if (!isDefaultColor(fg)) {
652         set_foreground_color(fg, outc);
653     }
654     if (!isDefaultColor(bg)) {
655         set_background_color(bg, outc);
656     }
657 }