hypr/subscribe_event.go

36 lines
607 B
Go

package hypr
import (
"bufio"
"context"
"strings"
"git.milar.in/milarin/slices"
)
func (i *Instance) Subscribe(ctx context.Context, events ...EventType) (<-chan Event, error) {
r, err := readSocketRaw(i.EventSocketPath(), strings.NewReader(""))
if err != nil {
return nil, err
}
out := make(chan Event, 10)
eventMap := slices.ToStructMap(events)
go func() {
defer r.Close()
defer close(out)
sc := bufio.NewScanner(r)
for ctx.Err() == nil && sc.Scan() {
event := parseEvent(sc.Text())
if _, ok := eventMap[event.Type]; ok {
out <- event
}
}
}()
return out, nil
}