| 1 |
package util |
| 2 |
|
| 3 |
import "sync" |
| 4 |
|
| 5 |
// EventType is the type for fzf events |
| 6 |
type EventType int |
| 7 |
|
| 8 |
// Events is a type that associates EventType to any data |
| 9 |
type Events map[EventType]any |
| 10 |
|
| 11 |
// EventBox is used for coordinating events |
| 12 |
type EventBox struct { |
| 13 |
events Events |
| 14 |
cond *sync.Cond |
| 15 |
ignore map[EventType]bool |
| 16 |
} |
| 17 |
|
| 18 |
// NewEventBox returns a new EventBox |
| 19 |
func NewEventBox() *EventBox { |
| 20 |
return &EventBox{ |
| 21 |
events: make(Events), |
| 22 |
cond: sync.NewCond(&sync.Mutex{}), |
| 23 |
ignore: make(map[EventType]bool)} |
| 24 |
} |
| 25 |
|
| 26 |
// Wait blocks the goroutine until signaled |
| 27 |
func (b *EventBox) Wait(callback func(*Events)) { |
| 28 |
b.cond.L.Lock() |
| 29 |
|
| 30 |
if len(b.events) == 0 { |
| 31 |
b.cond.Wait() |
| 32 |
} |
| 33 |
|
| 34 |
callback(&b.events) |
| 35 |
b.cond.L.Unlock() |
| 36 |
} |
| 37 |
|
| 38 |
// Set turns on the event type on the box |
| 39 |
func (b *EventBox) Set(event EventType, value any) { |
| 40 |
b.cond.L.Lock() |
| 41 |
b.events[event] = value |
| 42 |
if _, found := b.ignore[event]; !found { |
| 43 |
b.cond.Broadcast() |
| 44 |
} |
| 45 |
b.cond.L.Unlock() |
| 46 |
} |
| 47 |
|
| 48 |
// Clear clears the events |
| 49 |
// Unsynchronized; should be called within Wait routine |
| 50 |
func (events *Events) Clear() { |
| 51 |
for event := range *events { |
| 52 |
delete(*events, event) |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
// Peek peeks at the event box if the given event is set |
| 57 |
func (b *EventBox) Peek(event EventType) bool { |
| 58 |
b.cond.L.Lock() |
| 59 |
_, ok := b.events[event] |
| 60 |
b.cond.L.Unlock() |
| 61 |
return ok |
| 62 |
} |
| 63 |
|
| 64 |
// Watch deletes the events from the ignore list |
| 65 |
func (b *EventBox) Watch(events ...EventType) { |
| 66 |
b.cond.L.Lock() |
| 67 |
for _, event := range events { |
| 68 |
delete(b.ignore, event) |
| 69 |
} |
| 70 |
b.cond.L.Unlock() |
| 71 |
} |
| 72 |
|
| 73 |
// Unwatch adds the events to the ignore list |
| 74 |
func (b *EventBox) Unwatch(events ...EventType) { |
| 75 |
b.cond.L.Lock() |
| 76 |
for _, event := range events { |
| 77 |
b.ignore[event] = true |
| 78 |
} |
| 79 |
b.cond.L.Unlock() |
| 80 |
} |
| 81 |
|
| 82 |
// WaitFor blocks the execution until the event is received |
| 83 |
func (b *EventBox) WaitFor(event EventType) { |
| 84 |
looping := true |
| 85 |
for looping { |
| 86 |
b.Wait(func(events *Events) { |
| 87 |
for evt := range *events { |
| 88 |
switch evt { |
| 89 |
case event: |
| 90 |
looping = false |
| 91 |
return |
| 92 |
} |
| 93 |
} |
| 94 |
}) |
| 95 |
} |
| 96 |
} |