Browse Source

give dragger a synchronous API

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

71
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 {
event, err := x.NewButtonPressEvent(generic) for {
if err != nil { generic := <-s.events
log.Fatal(err) event, err := x.NewButtonPressEvent(generic)
} if err != nil {
log.Fatal(err)
code := generic.GetEventCode() }
if code == Pressed { if generic.GetEventCode() == Pressed {
s.pointerDown = true s.startedDrag = true
s.start = [2]int16{event.EventX, event.EventY} 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 { } else {
s.Done <- false s.end = [2]int16{event.EventX, event.EventY}
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]) 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