Created
June 21, 2022 18:43
-
-
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
This file contains hidden or 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 ( | |
"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