-
Notifications
You must be signed in to change notification settings - Fork 0
/
input.go
80 lines (68 loc) · 1.64 KB
/
input.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
package peco
import (
"time"
"github.com/nsf/termbox-go"
"golang.org/x/net/context"
)
func NewInput(state *Peco, am ActionMap, src chan termbox.Event) *Input {
return &Input{
actions: am,
evsrc: src,
state: state,
}
}
func (i *Input) Loop(ctx context.Context, cancel func()) error {
defer cancel()
for {
select {
case <-ctx.Done():
return nil
case ev := <-i.evsrc:
if err := i.handleInputEvent(ctx, ev); err != nil {
return nil
}
}
}
}
func (i *Input) handleInputEvent(ctx context.Context, ev termbox.Event) error {
switch ev.Type {
case termbox.EventError:
return nil
case termbox.EventResize:
i.state.Hub().SendDraw(nil)
return nil
case termbox.EventKey:
// ModAlt is a sequence of letters with a leading \x1b (=Esc).
// It would be nice if termbox differentiated this for us, but
// we workaround it by waiting (juuuust a few milliseconds) for
// extra key events. If no extra events arrive, it should be Esc
m := &i.mutex
// Smells like Esc or Alt. mod == nil checks for the presense
// of a previous timer
m.Lock()
if ev.Ch == 0 && ev.Key == 27 && i.mod == nil {
tmp := ev
i.mod = time.AfterFunc(50*time.Millisecond, func() {
m.Lock()
i.mod = nil
m.Unlock()
i.state.Keymap().ExecuteAction(ctx, i.state, tmp)
})
m.Unlock()
return nil
}
m.Unlock()
// it doesn't look like this is Esc or Alt. If we have a previous
// timer, stop it because this is probably Alt+ this new key
m.Lock()
if i.mod != nil {
i.mod.Stop()
i.mod = nil
ev.Mod |= termbox.ModAlt
}
m.Unlock()
i.state.Keymap().ExecuteAction(ctx, i.state, ev)
return nil
}
return nil
}