-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlive.go
72 lines (61 loc) · 1.18 KB
/
live.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
package balafon
import (
"fmt"
"io"
"unicode/utf8"
"gitlab.com/gomidi/midi/v2"
"gitlab.com/gomidi/midi/v2/drivers"
)
const (
// EOT is keycode for Ctrl+D.
EOT = 4
)
// LiveShell is an unbuffered live shell.
type LiveShell struct {
r io.Reader
it *Interpreter
buf []byte
out drivers.Out
}
// NewLiveShell creates a new live shell.
func NewLiveShell(r io.Reader, it *Interpreter, out drivers.Out) *LiveShell {
return &LiveShell{
r: r,
it: it,
buf: make([]byte, 1),
out: out,
}
}
// HandleNext handles the next character from input.
func (s *LiveShell) HandleNext() error {
_, err := s.r.Read(s.buf)
if err != nil {
return fmt.Errorf("error reading input: %w", err)
}
r, _ := utf8.DecodeRune(s.buf)
if r == EOT {
return io.EOF
}
if err := s.it.EvalString(string(r)); err != nil {
fmt.Printf("%s\n", err.Error())
return nil
}
for _, bar := range s.it.Flush() {
for _, ev := range bar.Events {
if ev.Message.Is(midi.NoteOnMsg) {
if err := s.out.Send(ev.Message); err != nil {
return err
}
}
}
}
return nil
}
// Run the shell.
func (s *LiveShell) Run() error {
for {
if err := s.HandleNext(); err != nil {
return err
}
}
}