10. All about color

10.1. The basics

Life seems dull with no colors. Curses has a nice mechanism to handle colors. Let's get into the thick of the things with a small program.

As you can see, to start using color, you should first call the function start_color(). After that you can use color capabilities of your terminals by various functions. To find out whether terminal has color capabilities or not, you can use has_colors() function, which returns FALSE if the terminal does not support color.

Curses initializes all the colors supported by terminal when start_color() is called. These can be accessed by the define constants like COLOR_BLACK etc. Now to actually start using colors, you have to define pairs. Colors are always used in pairs. That means you have to use the function init_pair() to define the foreground and background for the pair number you give. After that that pair number can be used as a normal attribute with COLOR_PAIR()function. This may seem to be cumbersome at first. But this elegant solution allows us to manage color pairs very easily. To appreciate it, you have to look into the the source code of "dialog", a utility for displaying dialog boxes from shell scripts. The developers have defined foreground and background combinations for all the colors they might need and initialized at the beginning. This makes it very easy to set attributes just by accessing a pair which we already have defined as a constant.

The following colors are defined in curses.h. You can use these as parameters for various color functions.
        COLOR_BLACK   0
        COLOR_RED     1
        COLOR_GREEN   2
        COLOR_YELLOW  3
        COLOR_BLUE    4
        COLOR_MAGENTA 5
        COLOR_CYAN    6
        COLOR_WHITE   7

10.2. Changing Color Definitions

The function init_color()can be used to change the rgb values for the colors defined by curses initially. Say you wanted to lighten the intensity of red color by a minuscule. Then you can use this function as

    init_color(COLOR_RED, 700, 0, 0);
    /* param 1     : color name
     * param 2, 3, 4 : rgb content min = 0, max = 1000 */

If your terminal cannot change the color definitions, the function returns ERR. The function can_change_color() can be used to find out whether the terminal has the capability of changing color content or not. The rgb content is scaled from 0 to 1000. Initially RED color is defined with content 1000(r), 0(g), 0(b).

10.3. Color Content

The functions color_content() and pair_content() can be used to find the color content and foreground, background combination for the pair.