rthornton128 / goncurses

NCurses Library for Go
Other
383 stars 51 forks source link

Changing colors within MenuItems #70

Open jonhiggs opened 1 year ago

jonhiggs commented 1 year ago

I cannot work out how to add color to a part of a MenuItem. When I try droping ansi sequences into the string, I get nothing...

Is there a better way to do this?

items := make([]*gc.MenuItem, 1)
//itemStr := string("\033[31m") + "hello" + string("\033[0m") + "world"
itemStr := fmt.Sprintf(string("\033[31m") + "hello" + string("\033[0m") + "world")
items[0], _ = gc.NewItem(itemStr, "")
defer items[0].Free()
servusdei2018 commented 1 year ago

@jonhiggs ncurses does not provide built-in support for adding color to specific parts of a MenuItem using ANSI escape sequences. It's important to remember that the library offers comprehensive documentation that can guide you through this process. In this case, taking the time to read the documentation will inform you regarding its color handling procedures and how this is achieved through attribute manipulation.

You may achieve the coloration of menu items like this:

package main

import (
    "github.com/rthornton128/goncurses"
)

func main() {
    stdscr, _ := goncurses.Init()
    defer goncurses.End()

    goncurses.StartColor()
    stdscr.Keypad(true)
    goncurses.Raw(true)

    if goncurses.HasColors() {
        // Initialize a red foreground, black background color pair.
        goncurses.InitPair(1, goncurses.C_RED, goncurses.C_BLACK)
    }

    menuItem1 := "Hello "
    menuItem2 := "world"

    menuItemRed, _ := goncurses.NewItem(menuItem1, "")
    menuItemNormal, _ := goncurses.NewItem(menuItem2, "")

    // Color the specified menu item red using the specified color pair
    menuItemRed.AttrOn(goncurses.ColorPair(1))

    menu := goncurses.NewMenu([]*goncurses.MenuItem{menuItemRed, menuItemNormal})
    defer menu.Free()

    stdscr.Print("Press Enter to exit")
    stdscr.Refresh()

    menu.Post()
    menu.Driver(goncurses.REQ_DOWN)

    for {
        ch := stdscr.GetChar()
        if ch == goncurses.KEY_ENTER || ch == goncurses.KEY_RETURN {
            break
        }
        menu.Driver(goncurses.DriverActions[ch])
        stdscr.Refresh()
    }

    menu.UnPost()
}