ui: add package input for merged input

To avoid passing a queue type for each kind of input (pointer, key),
introduce package input for mapping a handler key to all input events.

Future input sources can be added without changes to programs, and
as an added bonus, event ordering is preserved across input sources.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
This commit is contained in:
Elias Naur
2019-06-07 21:41:09 +02:00
parent 28dd25736f
commit a35118d522
10 changed files with 172 additions and 130 deletions
+53
View File
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: Unlicense OR MIT
package input
import (
"gioui.org/ui"
"gioui.org/ui/key"
"gioui.org/ui/pointer"
)
// Queue is an Events implementation that merges events from
// all available input sources.
type Queue struct {
pqueue pointerQueue
kqueue keyQueue
handlers handlerEvents
}
type handlerEvents map[Key][]Event
func (q *Queue) For(k Key) []Event {
return q.handlers[k]
}
func (q *Queue) Frame(ops *ui.Ops) {
q.init()
for k := range q.handlers {
delete(q.handlers, k)
}
q.pqueue.Frame(ops, q.handlers)
q.kqueue.Frame(ops, q.handlers)
}
func (q *Queue) Add(e Event) {
q.init()
switch e := e.(type) {
case pointer.Event:
q.pqueue.Push(e, q.handlers)
case key.Edit, key.Chord, key.Focus:
q.kqueue.Push(e, q.handlers)
}
}
func (q *Queue) InputState() key.TextInputState {
return q.kqueue.InputState()
}
func (q *Queue) init() {
if q.handlers == nil {
q.handlers = make(handlerEvents)
}
}