Skip to content
Myr

eventbox.go

This file

Path

src/util/eventbox.go

96 lines · 1.9 KiB · Go

Last changed by

Not known.

History of this file

Take it

1package util23import "sync"45// EventType is the type for fzf events6type EventType int78// Events is a type that associates EventType to any data9type Events map[EventType]any1011// EventBox is used for coordinating events12type EventBox struct {13	events Events14	cond   *sync.Cond15	ignore map[EventType]bool16}1718// NewEventBox returns a new EventBox19func NewEventBox() *EventBox {20	return &EventBox{21		events: make(Events),22		cond:   sync.NewCond(&sync.Mutex{}),23		ignore: make(map[EventType]bool)}24}2526// Wait blocks the goroutine until signaled27func (b *EventBox) Wait(callback func(*Events)) {28	b.cond.L.Lock()2930	if len(b.events) == 0 {31		b.cond.Wait()32	}3334	callback(&b.events)35	b.cond.L.Unlock()36}3738// Set turns on the event type on the box39func (b *EventBox) Set(event EventType, value any) {40	b.cond.L.Lock()41	b.events[event] = value42	if _, found := b.ignore[event]; !found {43		b.cond.Broadcast()44	}45	b.cond.L.Unlock()46}4748// Clear clears the events49// Unsynchronized; should be called within Wait routine50func (events *Events) Clear() {51	for event := range *events {52		delete(*events, event)53	}54}5556// Peek peeks at the event box if the given event is set57func (b *EventBox) Peek(event EventType) bool {58	b.cond.L.Lock()59	_, ok := b.events[event]60	b.cond.L.Unlock()61	return ok62}6364// Watch deletes the events from the ignore list65func (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}7273// Unwatch adds the events to the ignore list74func (b *EventBox) Unwatch(events ...EventType) {75	b.cond.L.Lock()76	for _, event := range events {77		b.ignore[event] = true78	}79	b.cond.L.Unlock()80}8182// WaitFor blocks the execution until the event is received83func (b *EventBox) WaitFor(event EventType) {84	looping := true85	for looping {86		b.Wait(func(events *Events) {87			for evt := range *events {88				switch evt {89				case event:90					looping = false91					return92				}93			}94		})95	}96}