From f69ed76700f9a9e69869ec2072adac4be9ab4c69 Mon Sep 17 00:00:00 2001 From: Pieter van Loon Date: Mon, 27 Dec 2021 11:01:39 +0100 Subject: [PATCH] Add mouse position demonstration to mouse example --- _examples/mouse.go | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/_examples/mouse.go b/_examples/mouse.go index 59774eb..5560bd0 100644 --- a/_examples/mouse.go +++ b/_examples/mouse.go @@ -34,12 +34,19 @@ func main() { } var initialMouseX, initialMouseY, xOffset int -var msgMouseDown, movingMsg bool +var globalMouseDown, msgMouseDown, movingMsg bool func layout(g *gocui.Gui) error { + maxX, maxY := g.Size() if _, err := g.View("msg"); msgMouseDown && err == nil { moveMsg(g) } + if v, err := g.SetView("global", -1, -1, maxX, maxY, 0); err != nil { + if !errors.Is(err, gocui.ErrUnknownView) { + return err + } + v.Frame = false + } if v, err := g.SetView("but1", 2, 2, 22, 7, 0); err != nil { if !errors.Is(err, gocui.ErrUnknownView) { return err @@ -78,6 +85,9 @@ func keybindings(g *gocui.Gui) error { if err := g.SetKeybinding("", gocui.MouseRelease, gocui.ModNone, mouseUp); err != nil { return err } + if err := g.SetKeybinding("", gocui.MouseLeft, gocui.ModNone, globalDown); err != nil { + return err + } if err := g.SetKeybinding("msg", gocui.MouseLeft, gocui.ModNone, msgDown); err != nil { return err } @@ -137,6 +147,26 @@ func msgDown(g *gocui.Gui, v *gocui.View) error { return nil } +func globalDown(g *gocui.Gui, v *gocui.View) error { + globalMouseDown = true + mx, my := g.MousePosition() + maxX, _ := g.Size() + msg := fmt.Sprintf("Mouse down at: %d,%d", mx, my) + x := mx - len(msg)/2 + if x < 0 { + x = 0 + } else if x+len(msg)+1 > maxX-1 { + x = maxX - 1 - len(msg) - 1 + } + if v, err := g.SetView("globalDown", x, my-1, x+len(msg)+1, my+1, 0); err != nil { + if !errors.Is(err, gocui.ErrUnknownView) { + return err + } + v.WriteString(msg) + } + return nil +} + func mouseUp(g *gocui.Gui, v *gocui.View) error { if msgMouseDown { msgMouseDown = false @@ -146,6 +176,9 @@ func mouseUp(g *gocui.Gui, v *gocui.View) error { } else { g.DeleteView("msg") } + } else if globalMouseDown { + globalMouseDown = false + g.DeleteView("globalDown") } return nil }