neko/server/internal/webrtc/cursor/position.go

75 lines
1.5 KiB
Go
Raw Normal View History

package cursor
import (
"reflect"
"sync"
"github.com/rs/zerolog"
)
2023-04-17 10:42:29 +12:00
type PositionListener interface {
SendCursorPosition(x, y int) error
}
type Position interface {
Shutdown()
Set(x, y int)
AddListener(listener PositionListener)
RemoveListener(listener PositionListener)
}
2023-04-17 10:42:29 +12:00
type position struct {
2022-02-15 06:41:47 +13:00
logger zerolog.Logger
2023-04-17 10:42:29 +12:00
listeners map[uintptr]PositionListener
listenersMu sync.RWMutex
}
func NewPosition(logger zerolog.Logger) *position {
return &position{
logger: logger.With().Str("submodule", "cursor-position").Logger(),
listeners: map[uintptr]PositionListener{},
}
}
2023-04-17 10:42:29 +12:00
func (manager *position) Shutdown() {
2021-08-30 04:59:46 +12:00
manager.logger.Info().Msg("shutdown")
2022-02-15 06:41:47 +13:00
manager.listenersMu.Lock()
for key := range manager.listeners {
delete(manager.listeners, key)
}
2022-02-15 06:41:47 +13:00
manager.listenersMu.Unlock()
}
2023-04-17 10:42:29 +12:00
func (manager *position) Set(x, y int) {
manager.listenersMu.RLock()
defer manager.listenersMu.RUnlock()
2022-02-15 06:41:47 +13:00
2023-04-17 10:42:29 +12:00
for _, l := range manager.listeners {
if err := l.SendCursorPosition(x, y); err != nil {
manager.logger.Err(err).Msg("failed to set cursor position")
}
2021-03-01 06:50:32 +13:00
}
}
2023-04-17 10:42:29 +12:00
func (manager *position) AddListener(listener PositionListener) {
2022-02-15 06:41:47 +13:00
manager.listenersMu.Lock()
defer manager.listenersMu.Unlock()
if listener != nil {
ptr := reflect.ValueOf(listener).Pointer()
manager.listeners[ptr] = listener
}
}
2023-04-17 10:42:29 +12:00
func (manager *position) RemoveListener(listener PositionListener) {
2022-02-15 06:41:47 +13:00
manager.listenersMu.Lock()
defer manager.listenersMu.Unlock()
if listener != nil {
ptr := reflect.ValueOf(listener).Pointer()
delete(manager.listeners, ptr)
}
}