Files
gio-patched/layout/context.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

74 lines
1.5 KiB
Go

// SPDX-License-Identifier: Unlicense OR MIT
package layout
import (
"image"
"math"
"time"
"gioui.org/io/event"
"gioui.org/io/system"
"gioui.org/op"
"gioui.org/unit"
)
// Context carries the state needed by almost all layouts and widgets.
// A zero value Context never returns events, map units to pixels
// with a scale of 1.0, and returns the zero time from Now.
type Context struct {
// Constraints track the constraints for the active widget or
// layout.
Constraints Constraints
Config system.Config
Queue event.Queue
*op.Ops
}
// NewContext is a shorthand for
//
// Context{
// Ops: ops,
// Queue: q,
// Config: cfg,
// Constraints: Exact(size),
// }
//
// NewContext calls ops.Reset.
func NewContext(ops *op.Ops, q event.Queue, cfg system.Config, size image.Point) Context {
ops.Reset()
return Context{
Ops: ops,
Queue: q,
Config: cfg,
Constraints: Exact(size),
}
}
// Now returns the configuration time or the zero time.
func (c Context) Now() time.Time {
if c.Config == nil {
return time.Time{}
}
return c.Config.Now()
}
// Px maps the value to pixels. If no configuration is set,
// Px returns the rounded value of v.
func (c Context) Px(v unit.Value) int {
if c.Config == nil {
return int(math.Round(float64(v.V)))
}
return c.Config.Px(v)
}
// Events returns the events available for the key. If no
// queue is configured, Events returns nil.
func (c Context) Events(k event.Tag) []event.Event {
if c.Queue == nil {
return nil
}
return c.Queue.Events(k)
}