jroimartin / gocui

Minimalist Go package aimed at creating Console User Interfaces.
BSD 3-Clause "New" or "Revised" License
9.92k stars 608 forks source link

Start printing at cursor position #232

Open dzonerzy opened 3 years ago

dzonerzy commented 3 years ago

Hi i want to create a custom widget , a button with text alignment, but seems like I can't use SetCursor / SetOrigin to start printing at cursor position, what i'm doing wrong??

package widgets

import (
    "fmt"

    "github.com/jroimartin/gocui"
)

var (
    ButtonID      = "Button"
    ButtonCounter = 0
)

type ButtonHandler func(b *Button) error

type Button struct {
    lrpadding   int
    tbpadding   int
    x           int
    y           int
    w           int
    h           int
    name        *Text
    label       *Text
    borderColor gocui.Attribute
    textColor   gocui.Attribute
    handler     func(g *gocui.Gui, v *gocui.View) error
}

func (b *Button) Layout(g *gocui.Gui) error {
    v, err := g.SetView(b.name.String(), b.x, b.y, b.x+b.w, b.y+b.h)
    if err != nil {
        if err != gocui.ErrUnknownView {
            return err
        }
        if _, err := g.SetCurrentView(b.name.String()); err != nil {
            return err
        }
        if err := g.SetKeybinding(b.name.String(), gocui.KeyEnter, gocui.ModNone, b.handler); err != nil {
            return err
        }
        v.SetCursor(1, 1)
        v.FgColor = b.textColor
        g.Highlight = true
        g.SelFgColor = b.borderColor
        g.Cursor = true
        fmt.Fprint(v, b.label.String())
    }
    return nil
}

func (b *Button) Resize() *Button {
    b.w += b.label.Len() + (b.lrpadding * 2)
    b.h += (b.tbpadding * 2)
    return b
}

func (b *Button) Color(borderColor, textColor gocui.Attribute) *Button {
    b.borderColor = borderColor
    b.textColor = textColor
    return b
}

func NewButton(label string, x, y int, handler ButtonHandler) *Button {
    ButtonCounter++
    return &Button{
        name:      NewText(fmt.Sprintf("#%s_%d", ButtonID, ButtonCounter)),
        label:     NewText(label),
        lrpadding: 1,
        tbpadding: 0,
        x:         x,
        y:         y,
        h:         2,
        w:         1,
        handler:   nil,
    }
}