tins2020/control.go

53 lines
1.1 KiB
Go
Raw Normal View History

2020-05-09 13:32:43 +00:00
package tins2020
import "github.com/veandco/go-sdl2/sdl"
type Control interface {
Init(*Context) error
Arrange(*Context, Rectangle)
2020-05-09 13:32:43 +00:00
Handle(*Context, sdl.Event)
Render(*Context)
}
type EventContextFn func(*Context)
type EventFn func()
type EventInterfaceFn func(interface{})
func EmptyEvent(fn EventFn) EventContextFn {
return func(*Context) { fn() }
}
2020-05-09 13:32:43 +00:00
type ControlBase struct {
Bounds Rectangle
IsMouseOver bool
OnLeftMouseButtonClick EventContextFn
2020-05-09 13:32:43 +00:00
}
func (b *ControlBase) Arrange(ctx *Context, bounds Rectangle) { b.Bounds = bounds }
func (b *ControlBase) Init(*Context) error { return nil }
2020-05-09 13:32:43 +00:00
func (b *ControlBase) Handle(ctx *Context, event sdl.Event) {
switch e := event.(type) {
case *sdl.MouseMotionEvent:
b.IsMouseOver = b.Bounds.IsPointInside(e.X, e.Y)
case *sdl.MouseButtonEvent:
if b.IsMouseOver && e.Button == sdl.BUTTON_LEFT && e.Type == sdl.MOUSEBUTTONDOWN {
b.Invoke(ctx, b.OnLeftMouseButtonClick)
}
}
}
func (b *ControlBase) Invoke(ctx *Context, fn EventContextFn) {
if fn == nil {
return
}
fn(ctx)
}
2020-05-09 13:32:43 +00:00
func (b *ControlBase) Render(*Context) {}