Skip to content

Commit

Permalink
Add mouse position demonstration to mouse example
Browse files Browse the repository at this point in the history
  • Loading branch information
Kavantix committed Dec 30, 2021
1 parent 84c30a9 commit f69ed76
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion _examples/mouse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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
Expand All @@ -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
}

0 comments on commit f69ed76

Please sign in to comment.