/
keyboard.go
236 lines (204 loc) · 4.79 KB
/
keyboard.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package bbox
import (
"fmt"
"time"
"github.com/nsf/termbox-go"
)
const (
TEMPO_TICK = 15
// test
// DECAY = 2 * time.Second
// KEEP_ALIVE = 5 * time.Second
// prod
DECAY = 3 * time.Minute
KEEP_ALIVE = 14 * time.Minute
)
type Button struct {
beat int
tick int
decay bool
}
// normal operation:
// beats -> emit -> msgs
// shtudown operation:
// '`' -> closing<- {timers.Stop(), close(msgs), close(emit)} -> termbox.Close()
type Keyboard struct {
keyMap map[Key]*Coord
beats Beats
timers [SOUNDS][BEATS]*time.Timer
keepAlive *time.Timer // ensure at least one beat is sent periodically to keep speaker alive
emit chan Button // single button press, keyboard->emitter
msgs []chan<- Beats // all beats, emitter->msgs
tempo chan<- int // tempo changes
closing chan struct{}
debug bool
}
func tbprint(x, y int, msg string) {
for _, c := range msg {
termbox.SetCell(x, y, c, termbox.ColorDefault, termbox.ColorDefault)
x++
}
}
func InitKeyboard(
msgs []chan<- Beats,
tempo chan<- int,
keyMap map[Key]*Coord,
debug bool,
) *Keyboard {
// termbox.Close() called when Render.Run() exits
err := termbox.Init()
if err != nil {
panic(err)
}
termbox.SetInputMode(termbox.InputAlt)
return &Keyboard{
keyMap: keyMap,
beats: Beats{},
msgs: msgs,
tempo: tempo,
emit: make(chan Button),
closing: make(chan struct{}),
debug: debug,
}
}
func (kb *Keyboard) Run() {
defer func() { kb.closing <- struct{}{} }()
go kb.emitter()
var current string
var curev termbox.Event
data := make([]byte, 0, 64)
// starter beat
kb.flip(1, 0)
kb.flip(1, 8)
for {
if cap(data)-len(data) < 32 {
newdata := make([]byte, len(data), len(data)+32)
copy(newdata, data)
data = newdata
}
beg := len(data)
d := data[beg : beg+32]
switch ev := termbox.PollRawEvent(d); ev.Type {
case termbox.EventRaw:
data = data[:beg+ev.N]
current = fmt.Sprintf("%s", data)
if current == "`" {
// triggers a deferred kb.closing, which closes the emitter
fmt.Printf("Keyboard closing\n")
return
}
for {
ev := termbox.ParseEvent(data)
if ev.N == 0 {
break
}
curev = ev
copy(data, data[curev.N:])
data = data[:len(data)-curev.N]
key := kb.keyMap[Key{ev.Ch, ev.Key}]
if key != nil {
kb.flip(key[0], key[1])
}
// for debugging output
if kb.debug {
tbprint(0, SOUNDS+1,
fmt.Sprintf("EventKey: k: %5d, c: %c", ev.Key, ev.Ch))
termbox.Flush()
}
}
case termbox.EventError:
panic(ev.Err)
}
}
}
func (kb *Keyboard) flip(beat int, tick int) {
kb.button(beat, tick, false)
}
func (kb *Keyboard) button(beat int, tick int, decay bool) {
kb.emit <- Button{beat: beat, tick: tick, decay: decay}
}
func (kb *Keyboard) allOff() bool {
for _, row := range kb.beats {
for _, beat := range row {
if beat {
return false
}
}
}
return true
}
func (kb *Keyboard) emitter() {
last := Button{}
for {
select {
case <-kb.closing:
// ensure all timers are stopped before closing kb.emit
if kb.keepAlive != nil {
kb.keepAlive.Stop()
}
for _, arr := range kb.timers {
for _, t := range arr {
if t != nil {
t.Stop()
}
}
}
for _, msg := range kb.msgs {
close(msg) // signals to other processes to quit
}
close(kb.emit)
fmt.Printf("Keyboard emitter closing\n")
return
case button, more := <-kb.emit:
if more {
// TODO: consider re-using timers
if kb.timers[button.beat][button.tick] != nil {
kb.timers[button.beat][button.tick].Stop()
}
if button.decay || kb.beats[button.beat][button.tick] {
// turning off
kb.beats[button.beat][button.tick] = false
// check for all beats off, if so, set a keepalive timer
if kb.allOff() {
kb.keepAlive = time.AfterFunc(KEEP_ALIVE, func() {
// enable a beat to keep the speaker alive
kb.flip(1, 0)
})
}
} else {
// turning on
kb.beats[button.beat][button.tick] = true
// set a decay timer
kb.timers[button.beat][button.tick] = time.AfterFunc(DECAY, func() {
kb.button(button.beat, button.tick, true)
})
// we've enabled a beat, kill keepAlive
if kb.keepAlive != nil {
kb.keepAlive.Stop()
}
}
// broadcast changes
for _, msg := range kb.msgs {
msg <- kb.beats
}
// if tempo change, broadcast
if button.tick == TEMPO_TICK && last.tick == TEMPO_TICK {
if button.beat == 0 && last.beat == 0 {
kb.tempo <- 4
} else if button.beat == 3 && last.beat == 3 {
kb.tempo <- -4
}
}
last = button
} else {
// we should never get here
fmt.Printf("closed on emit, invalid state")
panic(1)
}
}
}
}
func (kb *Keyboard) Close() {
// TODO: this doesn't block?
close(kb.closing)
}