Browse Source

give dragger a synchronous API

master
Alexander Avery 2 years ago
parent
commit
5239152db8
  1. 57
      main.go

57
main.go

@ -22,61 +22,45 @@ const (
)
type dragger struct {
Done chan bool
events chan x.GenericEvent
ctx context.Context
pointerDown bool
startedDrag bool
start [2]int16
end [2]int16
}
// NewDragger returns a new reference to a dragger.
// This dragger can only be used to watch one drag event.
func NewDragger(events chan x.GenericEvent, ctx context.Context) *dragger {
return &dragger{
Done: make(chan bool, 1),
events: events,
ctx: ctx,
}
}
// Watch begins the process of dragger watching for drag events
func (s *dragger) Watch() {
func (s *dragger) Watch(ctx context.Context) int {
c := make(chan int, 1)
for {
select {
case generic := <-s.events:
s.handleEvent(generic)
break
case _ = <-s.ctx.Done():
return
case c <- s.watch():
return <-c
case _ = <-ctx.Done():
return 0
}
}
}
func (s *dragger) handleEvent(generic x.GenericEvent) {
func (s *dragger) watch() int {
for {
generic := <-s.events
event, err := x.NewButtonPressEvent(generic)
if err != nil {
log.Fatal(err)
}
code := generic.GetEventCode()
if code == Pressed {
s.pointerDown = true
if generic.GetEventCode() == Pressed {
s.startedDrag = true
s.start = [2]int16{event.EventX, event.EventY}
} else {
s.end = [2]int16{event.EventX, event.EventY}
if s.pointerDown {
s.pointerDown = false
s.Done <- true
} else {
s.Done <- false
s.startedDrag = false
return s.distance()
}
}
}
// Distance returns the total distance of the drag event
func (s dragger) Distance() int {
func (s dragger) distance() int {
diffx := int(s.start[0] - s.end[0])
diffy := int(s.start[1] - s.end[1])
distance := math.Sqrt(float64((diffx * diffx) + (diffy * diffy)))
@ -118,19 +102,16 @@ func main() {
defer mousebind.UngrabPointer(display)
eventChan := display.MakeAndAddEventChan(1)
responseChan := make(chan int, 1)
ctx, cancel := context.WithCancel(context.Background())
dm := NewDragger(eventChan, ctx)
go dm.Watch()
d := dragger{events: eventChan}
for {
select {
case v := <-dm.Done:
if v {
fmt.Println(dm.Distance())
case responseChan <- d.Watch(ctx):
fmt.Println(<-responseChan)
os.Exit(0)
}
break
case <-stop:
cancel()
os.Exit(0)

Loading…
Cancel
Save