summaryrefslogtreecommitdiffstats
path: root/src/eventbox.go
blob: 95126cca5d6587d93a8a67d1a027f808c8e2cda3 (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
package fzf

import "sync"

type EventType int

type Events map[EventType]interface{}

type EventBox struct {
	events Events
	cond   *sync.Cond
	ignore map[EventType]bool
}

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

func (b *EventBox) Wait(callback func(*Events)) {
	b.cond.L.Lock()
	defer b.cond.L.Unlock()

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

	callback(&b.events)
}

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

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

func (b *EventBox) Peak(event EventType) bool {
	b.cond.L.Lock()
	defer b.cond.L.Unlock()
	_, ok := b.events[event]
	return ok
}

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

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