Skip to content

Instantly share code, notes, and snippets.

@tlehman
Created June 21, 2022 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tlehman/9874bb92b35a1ba39b90df13e7e2bbe3 to your computer and use it in GitHub Desktop.
Save tlehman/9874bb92b35a1ba39b90df13e7e2bbe3 to your computer and use it in GitHub Desktop.
Simple example of gocui that responds to the arrow keys by moving the message around on the screen
package main
import (
"errors"
"fmt"
"log"
"github.com/awesome-gocui/gocui"
)
var offsetX int = 0
var offsetY int = 0
func main() {
// Create the UI object
g, err := gocui.NewGui(gocui.OutputNormal, true)
if err != nil {
log.Panicln(err)
}
defer g.Close()
// Set the view layout manager
g.SetManagerFunc(layout)
// Define keystrokes
err = g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit)
if err != nil {
log.Panicln(err)
}
g.SetKeybinding("", gocui.KeyArrowDown, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error {
offsetY -= 1
return nil
})
g.SetKeybinding("", gocui.KeyArrowUp, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error {
offsetY += 1
return nil
})
g.SetKeybinding("", gocui.KeyArrowLeft, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error {
offsetX += 1
return nil
})
g.SetKeybinding("", gocui.KeyArrowRight, gocui.ModNone, func(g *gocui.Gui, v *gocui.View) error {
offsetX -= 1
return nil
})
if err != nil {
log.Panicln(err)
}
// Run the main loop
err = g.MainLoop()
if err != nil && !errors.Is(err, gocui.ErrQuit) {
log.Panicln(err)
}
}
func layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
v, err := g.SetView("hello", maxX/2-7-offsetX, maxY/2-offsetY, maxX/2+7-offsetX, maxY/2+2-offsetY, 0)
if err != nil {
if !errors.Is(err, gocui.ErrUnknownView) {
return err
}
_, err = g.SetCurrentView("hello")
if err != nil {
return err
}
fmt.Fprintln(v, "hello world")
}
return nil
}
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