summaryrefslogtreecommitdiffstats
path: root/src/util/eventbox.go
blob: b710cf1e8f14b32052ff8fcc6e45946fdd56ad4f (plain)
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package util

import "sync"

// EventType is the type for fzf events
type EventType int

// Events is a type that associates EventType to any data
type Events map[EventType]interface{}

// EventBox is used for coordinating events
type EventBox struct {
	events Events
	cond   *sync.Cond
	ignore map[EventType]bool
}

// NewEventBox returns a new EventBox
func NewEventBox() *EventBox {
	return &EventBox{
		events: make(Events),
		cond:   sync.NewCond(&sync.Mutex{}),
		ignore: make(map[EventType]bool)}
}

// Wait blocks the goroutine until signaled
func (b *EventBox) Wait(callback func(*Events)) {
	b.cond.L.Lock()

	if len(b.events) == 0 {
		b.cond.Wait()
	}

	callback(&b.events)
	b.cond.L.Unlock()
}

// Set turns on the event type on the box
func (b *EventBox) Set(event EventType, value interface{}) {
	b.cond.L.Lock()
	b.events[event] = value
	if _, found := b.ignore[event]; !found {
		b.cond.Broadcast()
	}
	b.cond.L.Unlock()
}

// Clear clears the events
// Unsynchronized; should be called within Wait routine
func (events *Events) Clear() {
	for event := range *events {
		delete(*events, event)
	}
}

// Peek peeks at the event box if the given event is set
func (b *EventBox) Peek(event EventType) bool {
	b.cond.L.Lock()
	_, ok := b.events[event]
	b.cond.L.Unlock()
	return ok
}

// Watch deletes the events from the ignore list
func (b *EventBox) Watch(events ...EventType) {
	b.cond.L.Lock()
	for _, event := range events {
		delete(b.ignore, event)
	}
	b.cond.L.Unlock()
}

// Unwatch adds the events to the ignore list
func (b *EventBox) Unwatch(events ...EventType) {
	b.cond.L.Lock()
	for _, event := range events {
		b.ignore[event] = true
	}
	b.cond.L.Unlock()
}

// WaitFor blocks the execution until the event is received
func (b *EventBox) WaitFor(event EventType) {
	looping := true
	for looping {
		b.Wait(func(events *Events) {
			for evt := range *events {
				switch evt {
				case event:
					looping = false
					return
				}
			}
		})
	}
}