forked from joejulian/gio
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>
This commit is contained in:
+8
-7
@@ -47,18 +47,18 @@ func Expanded(w Widget) StackChild {
|
||||
// Layout a stack of children. The position of the children are
|
||||
// determined by the specified order, but Stacked children are laid out
|
||||
// before Expanded children.
|
||||
func (s Stack) Layout(gtx *Context, children ...StackChild) {
|
||||
func (s Stack) Layout(gtx Context, children ...StackChild) Dimensions {
|
||||
var maxSZ image.Point
|
||||
// First lay out Stacked children.
|
||||
for i, w := range children {
|
||||
if w.expanded {
|
||||
continue
|
||||
}
|
||||
cs := gtx.Constraints
|
||||
cs.Min = image.Pt(0, 0)
|
||||
var m op.MacroOp
|
||||
m.Record(gtx.Ops)
|
||||
dims := ctxLayout(gtx, cs, w.widget)
|
||||
gtx := gtx
|
||||
gtx.Constraints.Min = image.Pt(0, 0)
|
||||
dims := w.widget(gtx)
|
||||
m.Stop()
|
||||
if w := dims.Size.X; w > maxSZ.X {
|
||||
maxSZ.X = w
|
||||
@@ -76,10 +76,11 @@ func (s Stack) Layout(gtx *Context, children ...StackChild) {
|
||||
}
|
||||
var m op.MacroOp
|
||||
m.Record(gtx.Ops)
|
||||
cs := Constraints{
|
||||
gtx := gtx
|
||||
gtx.Constraints = Constraints{
|
||||
Min: maxSZ, Max: gtx.Constraints.Max,
|
||||
}
|
||||
dims := ctxLayout(gtx, cs, w.widget)
|
||||
dims := w.widget(gtx)
|
||||
m.Stop()
|
||||
if w := dims.Size.X; w > maxSZ.X {
|
||||
maxSZ.X = w
|
||||
@@ -119,7 +120,7 @@ func (s Stack) Layout(gtx *Context, children ...StackChild) {
|
||||
}
|
||||
}
|
||||
}
|
||||
gtx.Dimensions = Dimensions{
|
||||
return Dimensions{
|
||||
Size: maxSZ,
|
||||
Baseline: baseline,
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user