hypr/subscribe_event.go

37 lines
649 B
Go

package hypr
import (
"bufio"
"context"
"strings"
"git.milar.in/milarin/slices"
)
func (i *Client) 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)
allEvents := len(events) == 0
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]; allEvents || ok {
out <- event
}
}
}()
return out, nil
}