github.com/gop9/olt@v0.0.0-20200202132135-d956aad50b08/gio/layout/context.go (about)

     1  // SPDX-License-Identifier: Unlicense OR MIT
     2  
     3  package layout
     4  
     5  import (
     6  	"image"
     7  	"math"
     8  	"time"
     9  
    10  	"github.com/gop9/olt/gio/io/event"
    11  	"github.com/gop9/olt/gio/io/system"
    12  	"github.com/gop9/olt/gio/op"
    13  	"github.com/gop9/olt/gio/unit"
    14  )
    15  
    16  // Context carries the state needed by almost all layouts and widgets.
    17  // A zero value Context never returns events, map units to pixels
    18  // with a scale of 1.0, and returns the zero time from Now.
    19  type Context struct {
    20  	// Constraints track the constraints for the active widget or
    21  	// layout.
    22  	Constraints Constraints
    23  	// Dimensions track the result of the most recent layout
    24  	// operation.
    25  	Dimensions Dimensions
    26  
    27  	cfg   system.Config
    28  	queue event.Queue
    29  	*op.Ops
    30  }
    31  
    32  // NewContext returns a Context for an event queue.
    33  func NewContext(q event.Queue) *Context {
    34  	return &Context{
    35  		queue: q,
    36  	}
    37  }
    38  
    39  // layout a widget with a set of constraints and return its
    40  // dimensions. The widget dimensions are constrained abd the previous
    41  // constraints are restored after layout.
    42  func ctxLayout(gtx *Context, cs Constraints, w Widget) Dimensions {
    43  	saved := gtx.Constraints
    44  	gtx.Constraints = cs
    45  	gtx.Dimensions = Dimensions{}
    46  	w()
    47  	gtx.Dimensions.Size = cs.Constrain(gtx.Dimensions.Size)
    48  	gtx.Constraints = saved
    49  	return gtx.Dimensions
    50  }
    51  
    52  // Reset the context. The constraints' minimum and maximum values are
    53  // set to the size.
    54  func (c *Context) Reset(cfg system.Config, size image.Point) {
    55  	c.Constraints = RigidConstraints(size)
    56  	c.Dimensions = Dimensions{}
    57  	c.cfg = cfg
    58  	if c.Ops == nil {
    59  		c.Ops = new(op.Ops)
    60  	}
    61  	c.Ops.Reset()
    62  }
    63  
    64  // Now returns the configuration time or the the zero time.
    65  func (c *Context) Now() time.Time {
    66  	if c.cfg == nil {
    67  		return time.Time{}
    68  	}
    69  	return c.cfg.Now()
    70  }
    71  
    72  // Px maps the value to pixels. If no configuration is set,
    73  // Px returns the rounded value of v.
    74  func (c *Context) Px(v unit.Value) int {
    75  	if c.cfg == nil {
    76  		return int(math.Round(float64(v.V)))
    77  	}
    78  	return c.cfg.Px(v)
    79  }
    80  
    81  // Events returns the events available for the key. If no
    82  // queue is configured, Events returns nil.
    83  func (c *Context) Events(k event.Key) []event.Event {
    84  	if c.queue == nil {
    85  		return nil
    86  	}
    87  	return c.queue.Events(k)
    88  }