-
Notifications
You must be signed in to change notification settings - Fork 50
/
input_android.go
96 lines (86 loc) · 2.5 KB
/
input_android.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
86
87
88
89
90
91
92
93
94
95
96
// +build android
package mandala
// #include <android/native_activity.h>
// #include <android/input.h>
import "C"
import (
"runtime"
"github.com/tideland/goas/v2/loop"
)
const LOOPER_ID_INPUT = 0
// The loop handles native input events.
func androidEventLoopFunc(event chan interface{}, looperCh chan *C.ALooper) loop.LoopFunc {
return func(l loop.Loop) error {
var inputQueue *C.AInputQueue
runtime.LockOSThread()
defer runtime.UnlockOSThread()
looper := C.ALooper_prepare(C.ALOOPER_PREPARE_ALLOW_NON_CALLBACKS)
if looper == nil {
Fatalf("ALooper_prepare returned nil")
}
looperCh <- looper
for {
select {
case untypedEvent := <-event:
switch event := untypedEvent.(type) {
case inputQueueCreatedEvent:
inputQueue = (*C.AInputQueue)(event.inputQueue)
C.AInputQueue_attachLooper(inputQueue, looper, LOOPER_ID_INPUT, nil, nil)
case inputQueueDestroyedEvent:
inputQueue = (*C.AInputQueue)(event.inputQueue)
C.AInputQueue_detachLooper(inputQueue)
}
default:
if inputQueue != nil {
ident := C.ALooper_pollAll(-1, nil, nil, nil)
switch ident {
case LOOPER_ID_INPUT:
processInput(inputQueue)
case C.ALOOPER_POLL_ERROR:
Fatalf("ALooper_pollAll returned ALOOPER_POLL_ERROR\n")
}
}
}
}
}
}
func dispatchEvent(nativeEvent *C.AInputEvent) bool {
switch C.AInputEvent_getType(nativeEvent) {
case C.AINPUT_EVENT_TYPE_MOTION:
action := C.AMotionEvent_getAction(nativeEvent) & C.AMOTION_EVENT_ACTION_MASK
switch action {
case C.AMOTION_EVENT_ACTION_UP:
down := false
x := float32(C.AMotionEvent_getX(nativeEvent, 0))
y := float32(C.AMotionEvent_getY(nativeEvent, 0))
event <- ActionUpDownEvent{Down: down, X: x, Y: y}
case C.AMOTION_EVENT_ACTION_DOWN:
down := true
x := float32(C.AMotionEvent_getX(nativeEvent, 0))
y := float32(C.AMotionEvent_getY(nativeEvent, 0))
event <- ActionUpDownEvent{Down: down, X: x, Y: y}
case C.AMOTION_EVENT_ACTION_MOVE:
x := float32(C.AMotionEvent_getX(nativeEvent, 0))
y := float32(C.AMotionEvent_getY(nativeEvent, 0))
event <- ActionMoveEvent{X: x, Y: y}
}
}
return false
}
func processInput(inputQueue *C.AInputQueue) {
var event *C.AInputEvent
for {
if ret := C.AInputQueue_getEvent(inputQueue, &event); ret < 0 {
break
}
if C.AInputQueue_preDispatchEvent(inputQueue, event) != 0 {
continue
}
handled := dispatchEvent(event)
var handledC C.int
if handled {
handledC = 1
}
C.AInputQueue_finishEvent(inputQueue, event, handledC)
}
}