golang-exercises/gocui-practice/main.go

157 lines
3.0 KiB
Go

package main
import (
//"bytes"
"fmt"
"io"
"log"
"os/exec"
"strings"
"time"
"github.com/jroimartin/gocui"
"github.com/nsf/termbox-go"
)
var input chan string
func main() {
g, err := gocui.NewGui(gocui.OutputNormal)
if err != nil {
log.Panicln(err)
}
defer g.Close()
g.SetManagerFunc(layout)
go counter()
g.Mouse = true
g.Cursor = true
initKeybindings(g)
if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
log.Panicln(err)
}
}
var numToIncrease int
func counter() {
for {
numToIncrease++
time.Sleep(time.Second)
termbox.Interrupt()
}
}
func layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
if v, err := g.SetView("test", maxX/2-20, maxY/2-18, maxX/2+20, maxY/2-15); err != nil {
if err != gocui.ErrUnknownView {
return err
}
fmt.Fprintln(v, "This is a reaaaaaaaally long message")
fmt.Fprintln(v, "Hello!")
}
if v, err := g.SetView("editor", maxX/2-20, maxY/2-13, maxX/2+20, maxY/2-6); err != nil {
if err != gocui.ErrUnknownView {
return err
}
if _, err := g.SetCurrentView("editor"); err != nil {
return err
}
v.Title = "Editing"
v.Editable = true
v.Wrap = true
fmt.Fprintln(v, "")
}
if v, err := g.SetView("quit", maxX/2-20, maxY/2, maxX/2+20, maxY/2+5); err != nil {
if err != gocui.ErrUnknownView {
return err
}
v.Title = "Quit button"
fmt.Fprintln(v, "Quit")
go func() {
for {
fmt.Fprintf(v, "\r%v", numToIncrease)
time.Sleep(time.Second)
}
}()
go func() {
for {
time.Sleep(time.Second)
fmt.Fprintln(v, "Henlo")
termbox.Interrupt()
msg := <-input
fmt.Fprintln(v, msg)
termbox.Interrupt()
}
}()
// go func(v *gocui.View) {
// for {
// message := <-input
// v.Clear()
// fmt.Println(message)
// // formattedMsg := bytes.NewBufferString(message)
// // cmd := exec.Command("notify-send", formattedMsg.String())
// // cmd.Run()
// // fmt.Fprintln(v, formattedMsg)
// }
// }(v)
}
return nil
}
func quitter(g *gocui.Gui, v *gocui.View) error {
return gocui.ErrQuit
}
func initKeybindings(g *gocui.Gui) error {
if err := g.SetKeybinding("editor", gocui.KeyCtrlA, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
v.Mask ^= '*'
return nil
}); err != nil {
return err
}
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quitter); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("quit", gocui.MouseLeft, gocui.ModNone, quitter); err != nil {
log.Panicln(err)
}
if err := g.SetKeybinding("editor", gocui.KeyEnter, gocui.ModNone,
func(g *gocui.Gui, v *gocui.View) error {
vb := v.ViewBuffer()
stringer := strings.NewReader(vb)
buf := new(strings.Builder)
_, err := io.Copy(buf, stringer)
if err != nil {
return err
}
strings.TrimRight(buf.String(), "\n")
cmd := exec.Command("notify-send", strings.TrimRight(buf.String(), "\n"))
cmd.Run()
v.Clear()
v.SetCursor(0, 0)
// go func(buf *strings.Builder) {
// input <- buf.String()
// }(buf)
return nil
}); err != nil {
return err
}
return nil
}