Files
gio/widget/material/checkable.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

65 lines
1.7 KiB
Go

// SPDX-License-Identifier: Unlicense OR MIT
package material
import (
"image"
"image/color"
"gioui.org/io/pointer"
"gioui.org/layout"
"gioui.org/op/paint"
"gioui.org/text"
"gioui.org/unit"
"gioui.org/widget"
)
type checkable struct {
Label string
Color color.RGBA
Font text.Font
TextSize unit.Value
IconColor color.RGBA
Size unit.Value
shaper text.Shaper
checkedStateIcon *widget.Icon
uncheckedStateIcon *widget.Icon
}
func (c *checkable) layout(gtx layout.Context, checked bool) layout.Dimensions {
var icon *widget.Icon
if checked {
icon = c.checkedStateIcon
} else {
icon = c.uncheckedStateIcon
}
min := gtx.Constraints.Min
dims := layout.Flex{Alignment: layout.Middle}.Layout(gtx,
layout.Rigid(func(gtx layout.Context) layout.Dimensions {
return layout.Center.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
return layout.UniformInset(unit.Dp(2)).Layout(gtx, func(gtx layout.Context) layout.Dimensions {
size := gtx.Px(c.Size)
icon.Color = c.IconColor
icon.Layout(gtx, unit.Px(float32(size)))
return layout.Dimensions{
Size: image.Point{X: size, Y: size},
}
})
})
}),
layout.Rigid(func(gtx layout.Context) layout.Dimensions {
gtx.Constraints.Min = min
return layout.W.Layout(gtx, func(gtx layout.Context) layout.Dimensions {
return layout.UniformInset(unit.Dp(2)).Layout(gtx, func(gtx layout.Context) layout.Dimensions {
paint.ColorOp{Color: c.Color}.Add(gtx.Ops)
return widget.Label{}.Layout(gtx, c.shaper, c.Font, c.TextSize, c.Label)
})
})
}),
)
pointer.Rect(image.Rectangle{Max: dims.Size}).Add(gtx.Ops)
return dims
}