Search code examples
ncursescurses

How to fill a full background color in Ncurses using derwin() subwindow function?


Is there a way to fill a full background color using derwin() subwindow function in Ncurses?

This is my program below. I am expecting all white background in the sonny subwindow but unfortunately not what I expected to appear.

#include <ncurses.h>

int main(void)
{
    WINDOW *pops,*sonny;
    int x2, y2, x4, y4;

    initscr();
    start_color();
    init_pair(1, COLOR_WHITE, COLOR_BLUE);
    init_pair(2, COLOR_BLACK, COLOR_WHITE);

    x2 = COLS >> 1;
    y2 = LINES >> 1;
    x4 = (COLS - x2) / 2;
    y4 = (LINES - y2) / 2;

    /* create parent and subwindow with derwin() */
    pops = newwin(y2, x2, y4, x4);
    sonny = derwin(pops, y4, x4, 7, 5);
    if (sonny == NULL) {
        endwin();
        puts("Unable to create subwindow\n");
        return(1);
    }

    /* color windows and splash some text */
    wbkgd(pops,COLOR_PAIR(1));
    mvwaddstr(pops, 2, 2, "Hello, son.");
    wrefresh(pops);
    wbkgd(sonny,COLOR_PAIR(2));
    wborder(sonny, 0, 0, 0, 0, 0, 0, 0, 0);
    mvwaddstr(sonny, 3, 3, "Hello, Dad.");
    wrefresh(sonny);
    wgetch(sonny);

    endwin();
    return 0;
}

derwin.c program


Solution

  • The result from derwin (like subwin) shares memory with the parent window:

    The subwindow shares memory with the window orig, its ancestor, so that changes made to one window will affect both windows.

    Keeping this in mind when reading the manpage for wbkgd:

    If the cell uses color, and that does not match the color in the current background, the library updates only the non-color attributes, first removing those which may have come from the current background, and then adding attributes from the new background.

    The background character for the derived window does not match the colors of the cells because that was set by the first wbkgd call, on the parent window:

        wbkgd(pops,COLOR_PAIR(1));
    

    You can make the background character of the derived window the same as that (without modifying the cells) using wbkgdset,

        wbkgdset(sonny,COLOR_PAIR(1));
    

    After doing that, the color of the background character matches the contents of the derived window, and this paragraph applies:

    If the cell uses color, and that matches the color in the current background, the library removes attributes which may have come from the current background and adds attributes from the new background. It finishes by setting the cell to use the color from the new background.