Files
gio-patched/widget/bool.go
T
Elias Naur 3af01a3f43 layout: change Widget to take explicit Context and return explicit Dimensions
Change the definition of Widget from the implicit

        type Widget func()

to the explicit functional

        type Widget func(gtx layout.Context) layout.Dimensions

The advantages are numerous:

- Clearer connection between the incoming context and the output dimensions.
- Returning the Dimensions are impossible to omit.
- Contexts passed by value, so its fields can be exported
and freely mutated by the program.

The only disadvantage is the longer function literals and the many "returns".
What tipped the scales in favour of the explicit Widget variant is that type
aliases can dramatically shorten the literals:

	type (
		C = layout.Context
		D = layout.Dimensions
	)

	widget := func(gtx C) D {
		...
	}

Note that the aliases are not part of the Gio API and it is up to each user
whether they want to use them.

Finally the Go proposal for lightweight function literals,
https://github.com/golang/go/issues/21498, may remove the disadvantage
completely in future.

Context becomes a plain struct with only public fields, and its Reset is
replaced by a NewContext convenience constructor.

Signed-off-by: Elias Naur <mail@eliasnaur.com>
2020-05-23 22:28:49 +02:00

37 lines
627 B
Go

package widget
import (
"gioui.org/gesture"
"gioui.org/layout"
)
type Bool struct {
Value bool
// Last is the last registered click.
Last Click
gesture gesture.Click
}
// Update the checked state according to incoming events,
// and reports whether Value changed.
func (b *Bool) Update(gtx layout.Context) bool {
was := b.Value
for _, e := range b.gesture.Events(gtx) {
switch e.Type {
case gesture.TypeClick:
b.Last = Click{
Time: gtx.Now(),
Position: e.Position,
}
b.Value = !b.Value
}
}
return b.Value != was
}
func (b *Bool) Layout(gtx layout.Context) {
b.gesture.Add(gtx.Ops)
}