diff --git a/app/widget/menu.go b/app/widget/menu.go index 23b59ce..2c66e40 100644 --- a/app/widget/menu.go +++ b/app/widget/menu.go @@ -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.buffer == nil { + if w.buffer == nil || w.buffer.Bounds().Size() != size { w.buffer = app.BufferFor(ctx.Display().ColorModel(), size) 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.SetPageSize(size.Y / 16) + // Clear the 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 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())) diff --git a/app/widget/menu_test.go b/app/widget/menu_test.go new file mode 100644 index 0000000..2b30e94 --- /dev/null +++ b/app/widget/menu_test.go @@ -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") + } +} diff --git a/context.go b/context.go index e12dd17..b423668 100644 --- a/context.go +++ b/context.go @@ -173,37 +173,32 @@ func (c *controllerContext) handleInput(event hardware.InputEvent) { if handler, ok := layout.(app.RotaryInputHandler); ok { log.WithField("layout", layout.String()).Debug("dispatch rotary input") handler.HandleRotary(c, event.Delta) + return } } } case hardware.RotaryPressEvent: - var handled bool for _, layout := range c.layouts { if layout.IsVisible() { if handler, ok := layout.(app.ButtonInputHandler); ok { log.WithField("layout", layout.String()).Debug("dispatch button press") handler.HandleButtonPress(c) - handled = true + return } } } - if !handled { - c.handleRotaryPress() - } + c.handleRotaryPress() case hardware.RotaryLongPressEvent: - var handled bool for _, layout := range c.layouts { if layout.IsVisible() { if handler, ok := layout.(app.ButtonInputHandler); ok { log.WithField("layout", layout.String()).Debug("dispatch button long press") handler.HandleButtonLongPress(c) - handled = true + return } } } - if !handled { - c.handleRotaryLongPress() - } + c.handleRotaryLongPress() default: log.Warn("unhandled input event") } diff --git a/context_test.go b/context_test.go index 4eb6f0a..f77389a 100644 --- a/context_test.go +++ b/context_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/BeatGlow/beatglow/app" + "github.com/BeatGlow/beatglow/hardware" ) 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) + } + } +} diff --git a/hardware/input/encoder.go b/hardware/input/encoder.go index 6aaa9de..7c877ec 100644 --- a/hardware/input/encoder.go +++ b/hardware/input/encoder.go @@ -10,7 +10,7 @@ import ( "github.com/BeatGlow/beatglow/hardware" ) -var LongPressDuration = 350 * time.Millisecond +var LongPressDuration = 750 * time.Millisecond type Encoder interface { hardware.Driver diff --git a/hardware/input/event.go b/hardware/input/event.go new file mode 100644 index 0000000..153463d --- /dev/null +++ b/hardware/input/event.go @@ -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 +} diff --git a/hardware/input/event_test.go b/hardware/input/event_test.go new file mode 100644 index 0000000..fd658e5 --- /dev/null +++ b/hardware/input/event_test.go @@ -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) + } + } +} diff --git a/hardware/input/input_linux.go b/hardware/input/input_linux.go index 87246f8..98997b0 100644 --- a/hardware/input/input_linux.go +++ b/hardware/input/input_linux.go @@ -1,13 +1,11 @@ package input import ( - "encoding/binary" "errors" - "fmt" "os" "path/filepath" + "strconv" "strings" - "time" "github.com/sirupsen/logrus" @@ -168,32 +166,16 @@ func linuxPheripherals() (ps []*linuxPheripheral, err error) { 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 { f, err := os.Open(name) if err != nil { return err } - var raw linuxInputEvent + defer f.Close() for { - if err := binary.Read(f, binary.LittleEndian, &raw); err != nil { - _ = f.Close() + raw, err := readLinuxInputEvent(f, strconv.IntSize/8) + if err != nil { return err } if err := cb(raw); err != nil { @@ -232,24 +214,28 @@ func (s *linuxButton) readEvents(events chan<- hardware.InputEvent) { WithField("input", "button"). WithField("path", s.p.path) - var last time.Time + var button buttonState err := readLinuxInputEvents(s.p.path, func(ev linuxInputEvent) error { - if ev.Code == 0 { - return nil // Ignore + if ev.Type != 1 || ev.Code == 0 { // EV_KEY only; ignore synchronization events. + return nil } - log.WithField("data", ev).Trace("button event") - var event hardware.InputEvent switch ev.Value { - case 0: // Released - if ev.Time().Sub(last) > LongPressDuration { + case 1: // Pressed; repeated presses must not restart the timer. + 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()} } else { event = hardware.RotaryPressEvent{Time: ev.Time()} } - case 1: // Pressed - last = ev.Time() + default: // Ignore key autorepeat and unknown values. return nil } @@ -297,7 +283,7 @@ func (s *linuxRotary) readEvents(events chan<- hardware.InputEvent) { WithField("path", s.p.path) 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 }