golang-exercises/tui-test/main.go

103 lines
2.2 KiB
Go

package main
import (
"fmt"
"github.com/jroimartin/gocui"
"log"
"strings"
)
func main() {
g, err := gocui.NewGui(gocui.OutputNormal)
if err != nil {
log.Panicln(err)
}
defer g.Close()
g.SetManagerFunc(layout)
g.Mouse = true
g.Cursor = true
initKeybindings(g)
if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
log.Panicln(err)
}
}
func quit(*gocui.Gui, *gocui.View) error {
return gocui.ErrQuit
}
func sendmsg(g *gocui.Gui, v *gocui.View) error {
chatbox, err := g.View("chatbox")
textarea, err := g.View("textarea")
if err != nil {
log.Panicln(err)
}
message := textarea.Buffer()
msg := string(message)
if msg == "" {
return nil
}
fmt.Fprintln(chatbox, strings.TrimRight(msg, "\n"))
textarea.Clear()
textarea.SetCursor(0, 0)
return nil
}
func initKeybindings(g *gocui.Gui) error {
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("button", gocui.MouseLeft, gocui.ModNone, sendmsg); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("textarea", gocui.KeyEnter, gocui.ModNone, sendmsg); err != nil {
log.Panicln(err)
}
return nil
}
func layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
if chatbox, err := g.SetView("chatbox", 2, 1, maxX/2+40, maxY/2+6); err != nil {
if err != gocui.ErrUnknownView {
return err
}
chatbox.Title = "Chat Box"
fmt.Fprintln(chatbox, "Hello world!")
}
if button, err := g.SetView("button", maxX/2+32, maxY/2+9, maxX/2+40, maxY/2+11); err != nil {
if err != gocui.ErrUnknownView {
return err
}
//button.BgColor = gocui.ColorRed
button.Wrap = true
button.Frame = true
fmt.Fprintln(button, "Send it")
}
if textarea, err := g.SetView("textarea", 2, maxY/2+9, maxX/2+25, maxY/2+11); err != nil {
if err != gocui.ErrUnknownView {
return err
}
if _, err := g.SetCurrentView("textarea"); err != nil {
log.Panicln(err)
}
textarea.Title = "Send message"
textarea.Wrap = true
textarea.Editable = true
}
// TODO: Add "Users currently online" view
// if currentUsers, err := g.SetView("currentUsers", maxX/2+34, 1, maxX/2+40, maxY/2+11); err != nil {
//
// }
return nil
}