-
Notifications
You must be signed in to change notification settings - Fork 1
/
gesture.go
85 lines (75 loc) · 2.12 KB
/
gesture.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"time"
"gioui.org/io/pointer"
"gioui.org/layout"
)
// LongPressType represents a successful or cancelled LongPress action.
type LongPressType uint8
const (
LongPressed LongPressType = iota
LongPressCancelled
)
// LongPressEvent represent a long press action
type LongPressEvent struct {
Type LongPressType
}
// LongPress detects a press-and-hold in the form of LongPress events
type LongPress struct {
pressedAt time.Time
// releasedAt tracks the pointer
releasedAt time.Time
// pressedFor tracks how long the press has been held so far.
pressedFor time.Duration
// detectAt tracks how long the press must be held.
detectAt time.Duration
// pressing tracks whether a press is occurring
pressed bool
timer *time.Timer
// callback is called when the timer fires
callback func()
}
// Update returns the next click event, if any.
func (l *LongPress) Update(gtx layout.Context) (*LongPressEvent, bool) {
// consume pointer events and start or stop a timer
filt := pointer.Filter{Target: l, Kinds: pointer.Press | pointer.Release | pointer.Leave}
if e, ok := gtx.Event(filt); ok {
if e, ok := e.(pointer.Event); ok {
switch e.Kind {
case pointer.Press:
l.pressedAt = time.Now()
l.timer = time.NewTimer(l.detectAt)
time.AfterFunc(l.detectAt, l.callback)
l.pressed = true
case pointer.Cancel, pointer.Release, pointer.Leave:
if l.pressed {
l.pressed = false
l.pressedFor = time.Now().Sub(l.pressedAt)
if !l.timer.Stop() {
<-l.timer.C
}
l.timer = nil
return &LongPressEvent{Type: LongPressCancelled}, true
}
}
}
}
// check if the timer has fired return a LongPressEvent
if l.timer != nil {
select {
case t := <-l.timer.C:
l.pressedFor = t.Sub(l.pressedAt)
if l.pressed {
l.pressed = false
l.pressedFor = time.Now().Sub(l.pressedAt)
return &LongPressEvent{Type: LongPressed}, true
}
default:
}
}
return &LongPressEvent{}, false
}
// NewLongPress returns a LongPress that triggers after the duration
func NewLongPress(cb func(), duration time.Duration) *LongPress {
return &LongPress{detectAt: duration, callback: cb}
}