zntg/ui/control.go

91 lines
1.8 KiB
Go
Raw Normal View History

2018-08-03 06:46:10 +00:00
package ui
import (
"time"
"opslag.de/schobers/geom"
2018-09-23 07:42:23 +00:00
"opslag.de/schobers/zntg/allg5"
2018-08-03 06:46:10 +00:00
)
type Control interface {
Created(Context, Container) error
Destroyed(Context)
Update(Context, time.Duration)
Handle(Context, allg5.Event)
2018-09-23 07:42:23 +00:00
DesiredSize(Context) geom.PointF32
Rect() geom.RectangleF32
SetRect(geom.RectangleF32)
2018-08-03 06:46:10 +00:00
Render(Context)
}
type MouseClickFn func(Control)
var _ Control = &ControlBase{}
type ControlBase struct {
Parent Container
2018-09-23 07:42:23 +00:00
Bounds geom.RectangleF32
2018-08-03 06:46:10 +00:00
Disabled bool
IsOver bool
IsPressed bool
OnClick MouseClickFn
2018-09-23 07:42:23 +00:00
MinSize geom.PointF32
Background *allg5.Color
2018-08-03 06:46:10 +00:00
}
func (c *ControlBase) Created(_ Context, p Container) error {
c.Parent = p
return nil
}
func (c *ControlBase) Destroyed(Context) {}
func (c *ControlBase) Update(Context, time.Duration) {}
func (c *ControlBase) Handle(ctx Context, ev allg5.Event) {
2018-08-03 06:46:10 +00:00
switch e := ev.(type) {
case *allg5.MouseMoveEvent:
2018-09-23 07:42:23 +00:00
c.IsOver = c.IsInRect(float32(e.X), float32(e.Y))
case *allg5.MouseButtonDownEvent:
2018-08-03 06:46:10 +00:00
if c.IsOver {
c.IsPressed = true
}
case *allg5.MouseButtonUpEvent:
2018-08-03 06:46:10 +00:00
if c.IsPressed && c.IsOver {
var onClick = c.OnClick
if nil != onClick {
onClick(c)
}
}
c.IsPressed = false
}
}
2018-09-23 07:42:23 +00:00
func (c *ControlBase) DesiredSize(Context) geom.PointF32 {
2018-08-03 06:46:10 +00:00
return c.MinSize
}
2018-09-23 07:42:23 +00:00
func (c *ControlBase) SetRect(rect geom.RectangleF32) {
2018-08-03 06:46:10 +00:00
c.Bounds = rect
}
func (c *ControlBase) Render(ctx Context) {
2018-09-23 07:42:23 +00:00
var min = c.Bounds.Min
var max = c.Bounds.Max
2018-08-03 06:46:10 +00:00
if nil != c.Background {
allg5.DrawFilledRectangle(min.X, min.Y, max.X, max.Y, *c.Background)
2018-08-03 06:46:10 +00:00
}
if ctx.Debug().IsEnabled() {
allg5.DrawRectangle(min.X, min.Y, max.X, max.Y, ctx.Debug().Rainbow(), 5)
2018-08-03 06:46:10 +00:00
}
}
2018-09-23 07:42:23 +00:00
func (c *ControlBase) Rect() geom.RectangleF32 {
2018-08-03 06:46:10 +00:00
return c.Bounds
}
2018-09-23 07:42:23 +00:00
func (c *ControlBase) IsInRect(x, y float32) bool {
return geom.PtF32(x, y).In(c.Bounds)
2018-08-03 06:46:10 +00:00
}