-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventloop.go
94 lines (80 loc) · 2.3 KB
/
eventloop.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
package main
import (
"fmt"
"github.com/BurntSushi/xgb"
"github.com/BurntSushi/xgb/xproto"
"github.com/BurntSushi/xgbutil"
"reflect"
)
func getEventName(ev xgb.Event) string {
return reflect.TypeOf(ev).Name()
}
func winFromValue(v reflect.Value) xproto.Window {
return xproto.Window(v.Uint())
}
func getEventWin(ev xgb.Event) []xproto.Window {
evVal := reflect.ValueOf(ev)
evType := evVal.Type()
var w xproto.Window
ret := make([]xproto.Window, 2)
if t := evType.Name(); t == "ConfigureRequestEvent" || t == "MapRequestEvent" {
ret = append(ret, winFromValue(evVal.FieldByName("Parent")))
}
if _, ok := evType.FieldByName("Window"); ok {
w = winFromValue(evVal.FieldByName("Window"))
} else if _, ok := evType.FieldByName("Event"); ok {
w = winFromValue(evVal.FieldByName("Event"))
} else if _, ok := evType.FieldByName("Owner"); ok {
w = winFromValue(evVal.FieldByName("Owner"))
} else if _, ok := evType.FieldByName("Requestor"); ok {
w = winFromValue(evVal.FieldByName("Requestor"))
}
return append(ret, w)
}
type EventCallback func(ev xgb.Event)
type EventLoop struct {
theEnd bool
X *xgbutil.XUtil
callbacks map[string]map[xproto.Window][]EventCallback
}
func NewEventLoop(X *xgbutil.XUtil) *EventLoop {
return &EventLoop{theEnd: false, X: X, callbacks: make(map[string]map[xproto.Window][]EventCallback)}
}
func (e *EventLoop) runCallbacks(event xgb.Event) {
for _, w := range getEventWin(event) {
callbacks, ok := e.callbacks[getEventName(event)][w]
if ok {
for _, c := range callbacks {
c(event)
}
}
}
}
func (e *EventLoop) Run() {
for !e.theEnd {
ev, err := e.X.Conn().WaitForEvent()
if ev != nil {
e.runCallbacks(ev)
}
if err != nil {
fmt.Println("got error:", err)
}
}
}
func (e *EventLoop) Stop() {
e.theEnd = true
}
func (e *EventLoop) AddCallback(eventName string, win xproto.Window, callback EventCallback) {
if _, ok := e.callbacks[eventName]; !ok {
e.callbacks[eventName] = make(map[xproto.Window][]EventCallback)
}
if _, ok := e.callbacks[eventName][win]; !ok {
e.callbacks[eventName][win] = make([]EventCallback, 0)
}
e.callbacks[eventName][win] = append(e.callbacks[eventName][win], callback)
}
func (e *EventLoop) DetachCallbacks(win xproto.Window) {
for evType := range e.callbacks {
delete(e.callbacks[evType], win)
}
}