color not ended in curses

2020-03-30 05:24发布

问题:

I am recently working on a game project using the curses library, and I used color-related functions like start_color(), init_color() and init_pair(). The color works well in my project, but once its used, the colors in other TUI applications like vim will go wrong.

For example: When I first edit some part of my code, it is like this:

This is vim with colorscheme slate, and it looks good.

However, when I run my code and exit and edit the code again, it become something like this:

Note: I did not change anything when I did this, and I thought that it is because I have changed the color definitions when I run my code. Also, if I use other functions, it will also go wrong, like:

But the original one should look like this:

I wanna know why this is happening, I thought there may be some ending functions of color I am not using, just like initscr() and endwin(), there should be another one for start_color(). Can anyone tell me why? Thanks a lot.

回答1:

For terminals that support it, init_color() has a different effect than the other color-related functions in ncurses. It changes the palette of colors used by any application:

If a terminal is capable of redefining colors, the programmer can use the routine init_color to change the definition of a color.

The palette is stored in the terminal emulator; every application which uses colors will use the same set of colors unless it modifies the palette via escape sequences. Those escape sequences are documented in XTerm Control Sequences.

ncurses has no way to determine what the palette of colors is at the start; it cannot restore the palette to its initial state on exit (e.g., in endwin). Unlike the color pair (default 0), there is no predefined palette used by all terminals which can produce color. To see this, compare the initc capability for these variations:

  • xterm (256 colors)
   initc=\E]4;%p1%d;rgb\:%p2%{255}%*%{1000}%/%2.2X/%p3%{255}%*%{1000}%/%2.2X/%p4%{255}%*%{1000}%/%2.2X\E\\,
  • Linux console (16 colors)
   initc=\E]P%p1%x%p2%{255}%*%{1000}%/%02x%p3%{255}%*%{1000}%/%02x%p4%{255}%*%{1000}%/%02x,

Because the only information that ncurses has is how to change the color, it cannot set the palette back to its original state on exit.

Further reading:

  • How to determine the current color of the console output?
  • ANSI/ECMA 48 color codes: getting background rendition


标签: c ncurses