3

On your favorite terminal, the special ANSI character for red text is ^[[31m. The special ANSI character for a blue background is ^[[44m. So, to have red text on a blue background would be ^[[31m^[[44mHello World!.

However, the library ncurses does things differently. Instead of having an individual red foreground character and a blue background character, you have COLOR_PAIRS. So, instead of having a program like this:

attron(RED_FG);
attron(BLUE_BG);
printw("Hello World!\n");
attroff(RED_FG); attroff(BLUE_BG); // Turn off the colors
refresh(); // Flush buffer to the screen

You have to do something like this:

init_pair(1, COLOR_RED, COLOR_BLUE); // Remember the number in the beginning!
attron(COLOR_PAIRS(1)); // Put it here!
printw("Hello World!\n");
attroff(COLOR_PAIRS(2)); // Remember to put the pair # here too
refresh();

I don't see why that ncurses has structured colors to be this way. What design pattern are they using, and how can I use this in my program whereas the color of the foreground and background would convey different attributes (say, in an ASCII-based game)?

3

ncurses uses the color pair approach because curses used it, and curses was build upon termcap which already used it to like this.

The root of all this is starts before ANSI escape sequences became widespread: termcap originating to 1978 and had to support as many as possible of existing terminals and vendor specific requirements at that date, and the ansi sequences were adopted as standard in 1979, and such transition doesn't happen overnight.

So the primary reason is certainly historical, i.e. finding a concept that would work with most of the terminals around.

I don't know very well the internals of termcap and its descendents. But I could imagine that the sharing of a console between several process could also have played a role in the design. The use of a color pair, allows more easily at context switch between processes to restore the current foreground and background colors that the current process was using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.