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 { type dragger struct {
Done chan bool
events chan x.GenericEvent events chan x.GenericEvent
ctx context.Context startedDrag bool
pointerDown bool
start [2]int16 start [2]int16
end [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 // 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 { for {
select { select {
case generic := <-s.events: case c <- s.watch():
s.handleEvent(generic) return <-c
break case _ = <-ctx.Done():
case _ = <-s.ctx.Done(): return 0
return
} }
} }
} }
func (s *dragger) handleEvent(generic x.GenericEvent) { func (s *dragger) watch() int {
for {
generic := <-s.events
event, err := x.NewButtonPressEvent(generic) event, err := x.NewButtonPressEvent(generic)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
code := generic.GetEventCode() if generic.GetEventCode() == Pressed {
s.startedDrag = true
if code == Pressed {
s.pointerDown = true
s.start = [2]int16{event.EventX, event.EventY} s.start = [2]int16{event.EventX, event.EventY}
} else { } else {
s.end = [2]int16{event.EventX, event.EventY} s.end = [2]int16{event.EventX, event.EventY}
if s.pointerDown { s.startedDrag = false
s.pointerDown = false return s.distance()
s.Done <- true
} else {
s.Done <- false
} }
} }
} }
// 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]) diffx := int(s.start[0] - s.end[0])
diffy := int(s.start[1] - s.end[1]) diffy := int(s.start[1] - s.end[1])
distance := math.Sqrt(float64((diffx * diffx) + (diffy * diffy))) distance := math.Sqrt(float64((diffx * diffx) + (diffy * diffy)))
@ -118,19 +102,16 @@ func main() {
defer mousebind.UngrabPointer(display) defer mousebind.UngrabPointer(display)
eventChan := display.MakeAndAddEventChan(1) eventChan := display.MakeAndAddEventChan(1)
responseChan := make(chan int, 1)
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
dm := NewDragger(eventChan, ctx) d := dragger{events: eventChan}
go dm.Watch()
for { for {
select { select {
case v := <-dm.Done: case responseChan <- d.Watch(ctx):
if v { fmt.Println(<-responseChan)
fmt.Println(dm.Distance())
os.Exit(0) os.Exit(0)
}
break
case <-stop: case <-stop:
cancel() cancel()
os.Exit(0) os.Exit(0)

Loading…
Cancel
Save