mirror of
https://git.sr.ht/~eliasnaur/gio
synced 2026-07-01 07:35:40 +00:00
d017c722f5
Before this change, events were typically processed twice or more per
widget: once in the Layout method for refreshing the visual state, and
once per method that queries for state changes.
One example is widget.Clickable that processed events in both its Layout
and Clicked method.
This change establishes the convention that events are processed once, in
the Layout method. There are several advantages to that approach:
- Query methods such as Clickable.Clicked no longer need a layout.Context.
- State updates from events only occur in Layout.
- Widgets are simplified because they won't need a separate processEvents
(or similar) method and won't forget to call it from methods other than Layout.
- Useless calls to gtx.Events are avoided (gtx.Events only returns events
for the first call each frame for a given event.Tag).
The disadvantage is that state updates from input events will not appear
before Layout. For example, in the call sequence
var btn *widget.Clickable
if btn.Clicked() {...}
btn.Layout(...)
the Clicked call will not detect an incoming click until the frame after it
happened.
This is ok because
- The Gio event router automatically dispatches an extra frame after events
arrive, bounding the latency from events to queries such as Clicked to
at most one frame (~17 ms).
- The potential extra frame of latency does not apply to Layout methods as long
as they process events before drawing. In other words, the visual feedback
from input events are not delayed because of this change.
Signed-off-by: Elias Naur <mail@eliasnaur.com>
52 lines
931 B
Go
52 lines
931 B
Go
package widget
|
|
|
|
import (
|
|
"gioui.org/gesture"
|
|
"gioui.org/layout"
|
|
)
|
|
|
|
type Enum struct {
|
|
Value string
|
|
|
|
changeVal string
|
|
|
|
clicks []gesture.Click
|
|
values []string
|
|
}
|
|
|
|
func index(vs []string, t string) int {
|
|
for i, v := range vs {
|
|
if v == t {
|
|
return i
|
|
}
|
|
}
|
|
return -1
|
|
}
|
|
|
|
// Changed reports whether Value has changed since the last
|
|
// call to Changed.
|
|
func (e *Enum) Changed() bool {
|
|
changed := e.changeVal != e.Value
|
|
e.changeVal = e.Value
|
|
return changed
|
|
}
|
|
|
|
// Layout adds the event handler for key.
|
|
func (e *Enum) Layout(gtx layout.Context, key string) {
|
|
if index(e.values, key) == -1 {
|
|
e.values = append(e.values, key)
|
|
e.clicks = append(e.clicks, gesture.Click{})
|
|
e.clicks[len(e.clicks)-1].Add(gtx.Ops)
|
|
} else {
|
|
idx := index(e.values, key)
|
|
clk := &e.clicks[idx]
|
|
for _, ev := range clk.Events(gtx) {
|
|
switch ev.Type {
|
|
case gesture.TypeClick:
|
|
e.Value = e.values[idx]
|
|
}
|
|
}
|
|
clk.Add(gtx.Ops)
|
|
}
|
|
}
|