Created
October 30, 2016 00:33
-
-
Save jroimartin/3b2e943a3811d795e0718b4a95b89bec to your computer and use it in GitHub Desktop.
gocui: simple input
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"strings" | |
"github.com/jroimartin/gocui" | |
) | |
type Label struct { | |
name string | |
x, y int | |
w, h int | |
body string | |
} | |
func NewLabel(name string, x, y int, body string) *Label { | |
lines := strings.Split(body, "\n") | |
w := 0 | |
for _, l := range lines { | |
if len(l) > w { | |
w = len(l) | |
} | |
} | |
h := len(lines) + 1 | |
w = w + 1 | |
return &Label{name: name, x: x, y: y, w: w, h: h, body: body} | |
} | |
func (l *Label) Layout(g *gocui.Gui) error { | |
v, err := g.SetView(l.name, l.x, l.y, l.x+l.w, l.y+l.h) | |
if err != nil { | |
if err != gocui.ErrUnknownView { | |
return err | |
} | |
v.Frame = false | |
fmt.Fprint(v, l.body) | |
} | |
return nil | |
} | |
type Input struct { | |
name string | |
x, y int | |
w int | |
maxLength int | |
} | |
func NewInput(name string, x, y, w, maxLength int) *Input { | |
return &Input{name: name, x: x, y: y, w: w, maxLength: maxLength} | |
} | |
func (i *Input) Layout(g *gocui.Gui) error { | |
v, err := g.SetView(i.name, i.x, i.y, i.x+i.w, i.y+2) | |
if err != nil { | |
if err != gocui.ErrUnknownView { | |
return err | |
} | |
v.Editor = i | |
v.Editable = true | |
} | |
return nil | |
} | |
func (i *Input) Edit(v *gocui.View, key gocui.Key, ch rune, mod gocui.Modifier) { | |
cx, _ := v.Cursor() | |
ox, _ := v.Origin() | |
limit := ox+cx+1 > i.maxLength | |
switch { | |
case ch != 0 && mod == 0 && !limit: | |
v.EditWrite(ch) | |
case key == gocui.KeySpace && !limit: | |
v.EditWrite(' ') | |
case key == gocui.KeyBackspace || key == gocui.KeyBackspace2: | |
v.EditDelete(true) | |
} | |
} | |
func SetFocus(name string) func(g *gocui.Gui) error { | |
return func(g *gocui.Gui) error { | |
_, err := g.SetCurrentView(name) | |
return err | |
} | |
} | |
func main() { | |
g, err := gocui.NewGui() | |
if err != nil { | |
log.Panicln(err) | |
} | |
defer g.Close() | |
g.Cursor = true | |
label := NewLabel("label", 1, 1, "Name") | |
input := NewInput("input", 7, 1, 20, 10) | |
focus := gocui.ManagerFunc(SetFocus("input")) | |
g.SetManager(label, input, focus) | |
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil { | |
log.Panicln(err) | |
} | |
if err := g.MainLoop(); err != nil && err != gocui.ErrQuit { | |
log.Panicln(err) | |
} | |
} | |
func quit(g *gocui.Gui, v *gocui.View) error { | |
return gocui.ErrQuit | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mode is required as the only argument for NewGui