hypr/subscribe_event.go

36 lines
607 B
Go
Raw Permalink Normal View History

2024-02-09 20:57:18 +01:00
package hypr
import (
"bufio"
2024-02-09 21:30:14 +01:00
"context"
2024-02-09 20:57:18 +01:00
"strings"
"git.milar.in/milarin/slices"
)
2024-02-09 21:30:14 +01:00
func (i *Instance) Subscribe(ctx context.Context, events ...EventType) (<-chan Event, error) {
2024-02-09 20:57:18 +01:00
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)
2024-02-09 21:30:14 +01:00
for ctx.Err() == nil && sc.Scan() {
2024-02-09 20:57:18 +01:00
event := parseEvent(sc.Text())
if _, ok := eventMap[event.Type]; ok {
out <- event
}
}
}()
return out, nil
}