112 lines
1.8 KiB
Go
112 lines
1.8 KiB
Go
package input
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
)
|
|
|
|
type Event interface {
|
|
String() string
|
|
|
|
// Source this event originated from.
|
|
Source() Source
|
|
|
|
// Time of the event.
|
|
Time() time.Time
|
|
}
|
|
|
|
type (
|
|
baseEvent struct {
|
|
source Source
|
|
time time.Time
|
|
}
|
|
|
|
// Button event.
|
|
Button struct {
|
|
baseEvent
|
|
|
|
// Pressed indicates if the button is pressed or released.
|
|
Pressed bool
|
|
}
|
|
|
|
// Rotary encoder event.
|
|
Rotary struct {
|
|
baseEvent
|
|
|
|
// Delta is the rate of change.
|
|
Delta int
|
|
|
|
// Switch indicates if the rotary switch is pressed or released.
|
|
Switch bool
|
|
}
|
|
|
|
// Key event.
|
|
Key struct {
|
|
baseEvent
|
|
|
|
// Pressed indicates if the key is pressed or released.
|
|
Pressed bool
|
|
|
|
// Code is the key scan code.
|
|
Code uint
|
|
}
|
|
)
|
|
|
|
func (e baseEvent) Source() Source { return e.source }
|
|
func (e baseEvent) Time() time.Time { return e.time }
|
|
func (e *baseEvent) SetTime(t time.Time) { e.time = t }
|
|
|
|
func makeBaseEvent(source Source) baseEvent {
|
|
return baseEvent{
|
|
source: source,
|
|
time: time.Now(),
|
|
}
|
|
}
|
|
|
|
func (e Button) String() string {
|
|
if e.Pressed {
|
|
return "button pressed"
|
|
}
|
|
return "button released"
|
|
}
|
|
|
|
func NewButtonEvent(source Source, pressed bool) Event {
|
|
return &Button{
|
|
baseEvent: makeBaseEvent(source),
|
|
Pressed: pressed,
|
|
}
|
|
}
|
|
|
|
func (e Rotary) String() string {
|
|
if e.Delta == 0 {
|
|
if e.Switch {
|
|
return "rotary pressed"
|
|
}
|
|
return "rotary released"
|
|
}
|
|
return fmt.Sprintf("rotary delta=%d", e.Delta)
|
|
}
|
|
|
|
func NewRotaryEvent(source Source, delta int, pressed bool) Event {
|
|
return &Rotary{
|
|
baseEvent: makeBaseEvent(source),
|
|
Delta: delta,
|
|
Switch: pressed,
|
|
}
|
|
}
|
|
|
|
func (e Key) String() string {
|
|
if e.Pressed {
|
|
return "key pressed"
|
|
}
|
|
return "key released"
|
|
}
|
|
|
|
func NewKeyEvent(source Source, pressed bool, code uint) Event {
|
|
return &Key{
|
|
baseEvent: makeBaseEvent(source),
|
|
Pressed: pressed,
|
|
Code: code,
|
|
}
|
|
}
|