Search code examples
rubycurses

How can I easily set the curses window background color in Ruby?


The ruby code below prints two windows (overlapping) via Curses. The first "border" window prints in black/cyan and the "content" window prints in blue on cyan.

The content window only displays the background color where text is printed. The rest of the content window remains black. The ruby dox describe ways to manipulate window backgrounds using either color_set, bkgd or bkgdset methods. I can only get color_set() to work however and only for text that is being printed:

enter image description here

How can I fill the reset of the content window with the appropriate background color? I found some code to Set a window's background color in Ruby curses but it does not seem to work and is quite old. The only other idea I have is to right-pad the string with spaces to fill the entire window with the background character but this seems reeealy hacky.

EDIT: added code

EDIT2: added "hacky padding" work around

    #!/usr/bin/ruby

    require 'curses'

    Curses.init_screen
    Curses.start_color
    Curses.noecho
    Curses.cbreak


    Curses.refresh  # Refresh the screen

    xulc = 10
    yulc = 10
    width = 30
    height = 8

    # text color for border window
    Curses.init_pair(1, Curses::COLOR_BLACK, Curses::COLOR_CYAN)
    Curses.attrset(Curses.color_pair(1) | Curses::A_BOLD)

    # Text color for content window
    Curses.init_pair(2, Curses::COLOR_BLUE, Curses::COLOR_CYAN)
    Curses.attrset(Curses.color_pair(2) | Curses::A_NORMAL)

    # border window   
    win1 = Curses::Window.new(height, width, yulc, xulc)
    win1.color_set(1)
    win1.box("|", "-")

    # content window
    win2 = Curses::Window.new(height - 2, width - 2, yulc + 1, xulc + 1)
    win2.color_set(2)
    win2.setpos(0, 0)

    # only prints in background color where there is text!
    # add hacky padding to fill background then go back and print message
    bg_padding = " " * ((width - 2) * (height - 2));
    win2.addstr(bg_padding);
    win2.setpos(0, 0)
    win2.addstr("blah")

    # prints without the color_set() attributes
    #win2.bkgd ('.'.ord)

    # make content visisble
    win1.refresh
    win2.refresh

    # hit a key to exit curses 
    Curses.getch 
    Curses.close_screen

Solution

  • Guess I'll use the hacky padding workaround. Seems to be all I've found so far