Fix button timing and event decoding and avoid redundant menu refreshes

This commit is contained in:
maze committed 2026-10-29 19:07:17 +01:00
1 parent 62b32c15cf
commit 494fa41420
8 files changed
+276 -44

No files matched your search

+5 -1
View File
@@ -55,7 +55,7 @@ func (w *Menu) Refresh(ctx app.Context) bool {
) )
if w.changed.CompareAndSwap(true, false) || w.buffer == nil || (w.curr != w.next && w.next != nil) { if w.changed.CompareAndSwap(true, false) || w.buffer == nil || (w.curr != w.next && w.next != nil) {
if w.buffer == nil { if w.buffer == nil || w.buffer.Bounds().Size() != size {
w.buffer = app.BufferFor(ctx.Display().ColorModel(), size) w.buffer = app.BufferFor(ctx.Display().ColorModel(), size)
w.Root.SetPageSize(size.Y / 16) w.Root.SetPageSize(size.Y / 16)
} }
@@ -64,6 +64,8 @@ func (w *Menu) Refresh(ctx app.Context) bool {
w.curr, w.next = w.next, nil w.curr, w.next = w.next, nil
} }
w.curr.SetPageSize(size.Y / 16)
// Clear the buffer. // Clear the buffer.
app.ImageClear(w.buffer) app.ImageClear(w.buffer)
@@ -102,6 +104,8 @@ func (w *Menu) Refresh(ctx app.Context) bool {
y := size.Y / len(menu.Items) * menu.Position y := size.Y / len(menu.Items) * menu.Position
draw.Box(w.buffer, image.Rect(size.X-3, y, size.X, y+size.Y/len(menu.Items)), color.Gray{Y: 0x7f}) draw.Box(w.buffer, image.Rect(size.X-3, y, size.X, y+size.Y/len(menu.Items)), color.Gray{Y: 0x7f})
} }
} else {
return false
} }
app.ImageCopyBounds(ctx.Display(), w.buffer, bounds.Add(w.position.Load())) app.ImageCopyBounds(ctx.Display(), w.buffer, bounds.Add(w.position.Load()))
+57
View File
@@ -0,0 +1,57 @@
package widget
import (
"image"
"image/color"
"testing"
"github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/app/menu"
"github.com/BeatGlow/display"
"github.com/BeatGlow/display/pixel"
)
type menuTestDisplay struct {
display.Display
image *image.RGBA
}
func (d *menuTestDisplay) Bounds() image.Rectangle { return d.image.Bounds() }
func (d *menuTestDisplay) ColorModel() color.Model { return pixel.Gray4Model }
func (d *menuTestDisplay) At(x, y int) color.Color { return d.image.At(x, y) }
func (d *menuTestDisplay) Set(x, y int, c color.Color) { d.image.Set(x, y, c) }
type menuTestContext struct {
app.Context
display display.Display
}
func (c *menuTestContext) Display() display.Display { return c.display }
func TestMenuRefreshOnlyOnChanges(t *testing.T) {
data := struct{ Enabled bool }{}
root, err := menu.New(&data, 4, nil)
if err != nil {
t.Fatal(err)
}
ctx := &menuTestContext{display: &menuTestDisplay{image: image.NewRGBA(image.Rect(0, 0, 256, 48))}}
w := NewMenu(image.Pt(256, 48), root)
w.SetStyles(*app.StylesFor(pixel.Gray4Model))
w.Show(ctx)
if !w.Refresh(ctx) {
t.Fatal("initial menu was not drawn")
}
if w.Refresh(ctx) {
t.Fatal("unchanged menu requested another hardware refresh")
}
root.Change(1)
w.Redraw()
if !w.Refresh(ctx) || w.Refresh(ctx) {
t.Fatal("menu change should trigger exactly one refresh")
}
w.Hide(ctx)
w.Show(ctx)
if !w.Refresh(ctx) {
t.Fatal("reopened menu was not drawn")
}
}
+5 -10
View File
@@ -173,37 +173,32 @@ func (c *controllerContext) handleInput(event hardware.InputEvent) {
if handler, ok := layout.(app.RotaryInputHandler); ok { if handler, ok := layout.(app.RotaryInputHandler); ok {
log.WithField("layout", layout.String()).Debug("dispatch rotary input") log.WithField("layout", layout.String()).Debug("dispatch rotary input")
handler.HandleRotary(c, event.Delta) handler.HandleRotary(c, event.Delta)
return
} }
} }
} }
case hardware.RotaryPressEvent: case hardware.RotaryPressEvent:
var handled bool
for _, layout := range c.layouts { for _, layout := range c.layouts {
if layout.IsVisible() { if layout.IsVisible() {
if handler, ok := layout.(app.ButtonInputHandler); ok { if handler, ok := layout.(app.ButtonInputHandler); ok {
log.WithField("layout", layout.String()).Debug("dispatch button press") log.WithField("layout", layout.String()).Debug("dispatch button press")
handler.HandleButtonPress(c) handler.HandleButtonPress(c)
handled = true return
} }
} }
} }
if !handled { c.handleRotaryPress()
c.handleRotaryPress()
}
case hardware.RotaryLongPressEvent: case hardware.RotaryLongPressEvent:
var handled bool
for _, layout := range c.layouts { for _, layout := range c.layouts {
if layout.IsVisible() { if layout.IsVisible() {
if handler, ok := layout.(app.ButtonInputHandler); ok { if handler, ok := layout.(app.ButtonInputHandler); ok {
log.WithField("layout", layout.String()).Debug("dispatch button long press") log.WithField("layout", layout.String()).Debug("dispatch button long press")
handler.HandleButtonLongPress(c) handler.HandleButtonLongPress(c)
handled = true return
} }
} }
} }
if !handled { c.handleRotaryLongPress()
c.handleRotaryLongPress()
}
default: default:
log.Warn("unhandled input event") log.Warn("unhandled input event")
} }
+33
View File
@@ -4,6 +4,7 @@ import (
"testing" "testing"
"github.com/BeatGlow/beatglow/app" "github.com/BeatGlow/beatglow/app"
"github.com/BeatGlow/beatglow/hardware"
) )
type navigationTestLayout struct { type navigationTestLayout struct {
@@ -35,3 +36,35 @@ func TestSettingsReturnsToActiveLayout(t *testing.T) {
} }
} }
} }
type inputTestLayout struct {
navigationTestLayout
onPress func(app.Context)
presses int
}
func (l *inputTestLayout) HandleButtonPress(ctx app.Context) {
l.presses++
if l.onPress != nil {
l.onPress(ctx)
}
}
func (l *inputTestLayout) HandleButtonLongPress(ctx app.Context) { l.HandleButtonPress(ctx) }
func TestButtonEventIsNotRedispatchedAfterScreenChange(t *testing.T) {
for _, long := range []bool{false, true} {
first := &inputTestLayout{navigationTestLayout: navigationTestLayout{name: "first"}}
second := &inputTestLayout{navigationTestLayout: navigationTestLayout{name: "second"}}
c := &controllerContext{layouts: []app.Layout{first, second}}
c.Show(first)
first.onPress = func(ctx app.Context) { ctx.Show(second) }
if long {
c.handleInput(hardware.RotaryLongPressEvent{})
} else {
c.handleInput(hardware.RotaryPressEvent{})
}
if first.presses != 1 || second.presses != 0 {
t.Fatalf("event was redispatched: first=%d second=%d", first.presses, second.presses)
}
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/BeatGlow/beatglow/hardware" "github.com/BeatGlow/beatglow/hardware"
) )
var LongPressDuration = 350 * time.Millisecond var LongPressDuration = 750 * time.Millisecond
type Encoder interface { type Encoder interface {
hardware.Driver hardware.Driver
+72
View File
@@ -0,0 +1,72 @@
package input
import (
"encoding/binary"
"fmt"
"io"
"time"
)
// linuxInputEvent holds a decoded evdev record, independent of native word size.
type linuxInputEvent struct {
Secs, USecs int64
Type, Code uint16
Value int32
}
func (e linuxInputEvent) String() string {
return fmt.Sprintf("time=%s type=%#04x code=%#04x value=%d", e.Time(), e.Type, e.Code, e.Value)
}
func (e linuxInputEvent) Time() time.Time {
return time.Unix(e.Secs, e.USecs*int64(time.Microsecond))
}
// readLinuxInputEvent reads one little-endian Linux event for a 4- or 8-byte
// native word. Short records return the error from io.ReadFull.
func readLinuxInputEvent(r io.Reader, wordSize int) (linuxInputEvent, error) {
var e linuxInputEvent
if wordSize != 4 && wordSize != 8 {
return e, fmt.Errorf("input: unsupported word size %d", wordSize)
}
var data [24]byte
if _, err := io.ReadFull(r, data[:2*wordSize+8]); err != nil {
return e, err
}
if wordSize == 4 {
e.Secs = int64(int32(binary.LittleEndian.Uint32(data[:4])))
e.USecs = int64(binary.LittleEndian.Uint32(data[4:8]))
} else {
e.Secs = int64(binary.LittleEndian.Uint64(data[:8]))
e.USecs = int64(binary.LittleEndian.Uint64(data[8:16]))
}
offset := 2 * wordSize
e.Type = binary.LittleEndian.Uint16(data[offset:])
e.Code = binary.LittleEndian.Uint16(data[offset+2:])
e.Value = int32(binary.LittleEndian.Uint32(data[offset+4:]))
return e, nil
}
// buttonState pairs one press with one release and ignores contact bounce.
// Access is confined to the button's event-reading goroutine.
type buttonState struct {
pressedAt, releasedAt time.Time
pressed bool
}
func (b *buttonState) press(at time.Time) {
if b.pressed || (!b.releasedAt.IsZero() && at.Sub(b.releasedAt) < 30*time.Millisecond) {
return
}
b.pressedAt, b.pressed = at, true
}
func (b *buttonState) release(at time.Time) (time.Duration, bool) {
if !b.pressed {
return 0, false
}
b.pressed = false
b.releasedAt = at
duration := at.Sub(b.pressedAt)
return duration, duration >= 0
}
+85
View File
@@ -0,0 +1,85 @@
package input
import (
"bytes"
"encoding/binary"
"errors"
"io"
"testing"
"time"
)
func TestInputEventRecordSizes(t *testing.T) {
for _, wordSize := range []int{4, 8} {
var stream bytes.Buffer
for _, value := range []int32{1, 0} {
if wordSize == 4 {
binary.Write(&stream, binary.LittleEndian, uint32(100))
binary.Write(&stream, binary.LittleEndian, uint32(950000))
} else {
binary.Write(&stream, binary.LittleEndian, uint64(100))
binary.Write(&stream, binary.LittleEndian, uint64(950000))
}
binary.Write(&stream, binary.LittleEndian, uint16(1))
binary.Write(&stream, binary.LittleEndian, uint16(28))
binary.Write(&stream, binary.LittleEndian, value)
}
for _, value := range []int32{1, 0} {
event, err := readLinuxInputEvent(&stream, wordSize)
if err != nil {
t.Fatal(err)
}
if event.Type != 1 || event.Code != 28 || event.Value != value {
t.Fatalf("wordSize=%d: misaligned event %+v", wordSize, event)
}
if !event.Time().Equal(time.Unix(100, 950000000)) {
t.Fatal("microseconds decoded incorrectly")
}
}
if _, err := readLinuxInputEvent(&stream, wordSize); !errors.Is(err, io.EOF) {
t.Fatalf("got %v, want EOF", err)
}
}
}
func TestButtonShortPressAcrossSecondBoundary(t *testing.T) {
var b buttonState
b.press((linuxInputEvent{Secs: 100, USecs: 950000}).Time())
duration, ok := b.release((linuxInputEvent{Secs: 101, USecs: 50000}).Time())
if !ok || duration != 100*time.Millisecond {
t.Fatalf("got %s, %v, want 100ms short press", duration, ok)
}
}
func TestButtonIgnoresDuplicateAndBouncedEvents(t *testing.T) {
var b buttonState
start := time.Unix(100, 0)
if _, ok := b.release(start); ok {
t.Fatal("unpaired release produced a click")
}
b.press(start)
b.press(start.Add(200 * time.Millisecond))
if duration, ok := b.release(start.Add(500 * time.Millisecond)); !ok || duration != 500*time.Millisecond {
t.Fatal("repeated press reset the long-press timer")
}
if _, ok := b.release(start.Add(501 * time.Millisecond)); ok {
t.Fatal("duplicate release produced a second click")
}
b.press(start.Add(505 * time.Millisecond))
if _, ok := b.release(start.Add(510 * time.Millisecond)); ok {
t.Fatal("contact bounce produced another click")
}
b.press(start.Add(time.Second))
if duration, ok := b.release(start.Add(1100 * time.Millisecond)); !ok || duration != 100*time.Millisecond {
t.Fatal("subsequent intentional click lost")
}
}
func TestTruncatedInputEvent(t *testing.T) {
for _, wordSize := range []int{4, 8} {
_, err := readLinuxInputEvent(bytes.NewReader(make([]byte, 2*wordSize+7)), wordSize)
if !errors.Is(err, io.ErrUnexpectedEOF) {
t.Fatalf("got %v, want unexpected EOF", err)
}
}
}
+18 -32
View File
@@ -1,13 +1,11 @@
package input package input
import ( import (
"encoding/binary"
"errors" "errors"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"strings" "strings"
"time"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@@ -168,32 +166,16 @@ func linuxPheripherals() (ps []*linuxPheripheral, err error) {
return ps, nil return ps, nil
} }
type linuxInputEvent struct {
Secs uint32
USecs uint32
Type uint16
Code uint16
Value int32
}
func (e linuxInputEvent) String() string {
return fmt.Sprintf("time=%s type=%#04x code=%#04x value=%d", e.Time(), e.Type, e.Code, e.Value)
}
func (e linuxInputEvent) Time() time.Time {
return time.Unix(int64(e.Secs), int64(e.USecs))
}
func readLinuxInputEvents(name string, cb func(linuxInputEvent) error) error { func readLinuxInputEvents(name string, cb func(linuxInputEvent) error) error {
f, err := os.Open(name) f, err := os.Open(name)
if err != nil { if err != nil {
return err return err
} }
var raw linuxInputEvent defer f.Close()
for { for {
if err := binary.Read(f, binary.LittleEndian, &raw); err != nil { raw, err := readLinuxInputEvent(f, strconv.IntSize/8)
_ = f.Close() if err != nil {
return err return err
} }
if err := cb(raw); err != nil { if err := cb(raw); err != nil {
@@ -232,24 +214,28 @@ func (s *linuxButton) readEvents(events chan<- hardware.InputEvent) {
WithField("input", "button"). WithField("input", "button").
WithField("path", s.p.path) WithField("path", s.p.path)
var last time.Time var button buttonState
err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error { err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error {
if ev.Code == 0 { if ev.Type != 1 || ev.Code == 0 { // EV_KEY only; ignore synchronization events.
return nil // Ignore return nil
} }
log.WithField("data", ev).Trace("button event")
var event hardware.InputEvent var event hardware.InputEvent
switch ev.Value { switch ev.Value {
case 0: // Released case 1: // Pressed; repeated presses must not restart the timer.
if ev.Time().Sub(last) > LongPressDuration { button.press(ev.Time())
return nil
case 0: // Released.
duration, ok := button.release(ev.Time())
if !ok {
return nil
}
if duration >= LongPressDuration {
event = hardware.RotaryLongPressEvent{Time: ev.Time()} event = hardware.RotaryLongPressEvent{Time: ev.Time()}
} else { } else {
event = hardware.RotaryPressEvent{Time: ev.Time()} event = hardware.RotaryPressEvent{Time: ev.Time()}
} }
case 1: // Pressed default: // Ignore key autorepeat and unknown values.
last = ev.Time()
return nil return nil
} }
@@ -297,7 +283,7 @@ func (s *linuxRotary) readEvents(events chan<- hardware.InputEvent) {
WithField("path", s.p.path) WithField("path", s.p.path)
err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error { err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error {
if ev.Value == 0 { if ev.Type != 2 || ev.Value == 0 { // EV_REL only.
return nil // Ignore return nil // Ignore
} }