gocui icon indicating copy to clipboard operation
gocui copied to clipboard

Start printing at cursor position

Open dzonerzy opened this issue 4 years ago • 0 comments

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,
	}
}

dzonerzy avatar Sep 15 '21 10:09 dzonerzy