2024-08-20 23:56:48 +02:00
|
|
|
// Copyright 2024, Command Line Inc.
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
|
|
|
package wshutil
|
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/google/uuid"
|
2024-09-12 03:03:55 +02:00
|
|
|
"github.com/wavetermdev/waveterm/pkg/wps"
|
2024-08-20 23:56:48 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
// event inverter. converts WaveEvents to a listener.On() API
|
|
|
|
|
|
|
|
type singleListener struct {
|
|
|
|
Id string
|
2024-09-12 03:03:55 +02:00
|
|
|
Fn func(*wps.WaveEvent)
|
2024-08-20 23:56:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type EventListener struct {
|
|
|
|
Lock *sync.Mutex
|
|
|
|
Listeners map[string][]singleListener
|
|
|
|
}
|
|
|
|
|
|
|
|
func MakeEventListener() *EventListener {
|
|
|
|
return &EventListener{
|
|
|
|
Lock: &sync.Mutex{},
|
|
|
|
Listeners: make(map[string][]singleListener),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-09-12 03:03:55 +02:00
|
|
|
func (el *EventListener) On(eventName string, fn func(*wps.WaveEvent)) string {
|
2024-08-20 23:56:48 +02:00
|
|
|
id := uuid.New().String()
|
|
|
|
el.Lock.Lock()
|
|
|
|
defer el.Lock.Unlock()
|
|
|
|
larr := el.Listeners[eventName]
|
|
|
|
larr = append(larr, singleListener{Id: id, Fn: fn})
|
|
|
|
el.Listeners[eventName] = larr
|
|
|
|
return id
|
|
|
|
}
|
|
|
|
|
|
|
|
func (el *EventListener) Unregister(eventName string, id string) {
|
|
|
|
el.Lock.Lock()
|
|
|
|
defer el.Lock.Unlock()
|
|
|
|
larr := el.Listeners[eventName]
|
|
|
|
newArr := make([]singleListener, 0)
|
|
|
|
for _, sl := range larr {
|
|
|
|
if sl.Id == id {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
newArr = append(newArr, sl)
|
|
|
|
}
|
|
|
|
el.Listeners[eventName] = newArr
|
|
|
|
}
|
|
|
|
|
|
|
|
func (el *EventListener) getListeners(eventName string) []singleListener {
|
|
|
|
el.Lock.Lock()
|
|
|
|
defer el.Lock.Unlock()
|
|
|
|
return el.Listeners[eventName]
|
|
|
|
}
|
|
|
|
|
2024-09-12 03:03:55 +02:00
|
|
|
func (el *EventListener) RecvEvent(e *wps.WaveEvent) {
|
2024-08-20 23:56:48 +02:00
|
|
|
larr := el.getListeners(e.Event)
|
|
|
|
for _, sl := range larr {
|
|
|
|
sl.Fn(e)
|
|
|
|
}
|
|
|
|
}
|