2020-05-09 13:32:43 +00:00
|
|
|
package tins2020
|
|
|
|
|
|
|
|
import "github.com/veandco/go-sdl2/sdl"
|
|
|
|
|
|
|
|
type Control interface {
|
|
|
|
Init(*Context) error
|
2020-05-10 15:16:18 +00:00
|
|
|
Arrange(*Context, Rectangle)
|
2020-05-11 09:44:50 +00:00
|
|
|
Handle(*Context, sdl.Event) bool
|
2020-05-09 13:32:43 +00:00
|
|
|
Render(*Context)
|
|
|
|
}
|
|
|
|
|
2020-05-10 18:44:20 +00:00
|
|
|
type EventContextFn func(*Context)
|
2020-05-10 15:16:18 +00:00
|
|
|
|
2020-05-10 18:44:20 +00:00
|
|
|
type EventFn func()
|
2020-05-10 15:16:18 +00:00
|
|
|
|
2020-05-10 18:44:20 +00:00
|
|
|
type EventInterfaceFn func(interface{})
|
|
|
|
|
|
|
|
func EmptyEvent(fn EventFn) EventContextFn {
|
2020-05-10 15:16:18 +00:00
|
|
|
return func(*Context) { fn() }
|
|
|
|
}
|
|
|
|
|
2020-05-09 13:32:43 +00:00
|
|
|
type ControlBase struct {
|
2020-05-10 10:21:51 +00:00
|
|
|
Bounds Rectangle
|
|
|
|
|
|
|
|
IsMouseOver bool
|
2020-05-10 15:16:18 +00:00
|
|
|
|
2020-05-10 18:44:20 +00:00
|
|
|
OnLeftMouseButtonClick EventContextFn
|
2020-05-09 13:32:43 +00:00
|
|
|
}
|
|
|
|
|
2020-05-10 15:16:18 +00:00
|
|
|
func (b *ControlBase) Arrange(ctx *Context, bounds Rectangle) { b.Bounds = bounds }
|
|
|
|
|
2020-05-10 10:21:51 +00:00
|
|
|
func (b *ControlBase) Init(*Context) error { return nil }
|
2020-05-09 13:32:43 +00:00
|
|
|
|
2020-05-11 09:44:50 +00:00
|
|
|
func (b *ControlBase) Handle(ctx *Context, event sdl.Event) bool {
|
2020-05-10 10:21:51 +00:00
|
|
|
switch e := event.(type) {
|
|
|
|
case *sdl.MouseMotionEvent:
|
|
|
|
b.IsMouseOver = b.Bounds.IsPointInside(e.X, e.Y)
|
2020-05-10 15:16:18 +00:00
|
|
|
case *sdl.MouseButtonEvent:
|
|
|
|
if b.IsMouseOver && e.Button == sdl.BUTTON_LEFT && e.Type == sdl.MOUSEBUTTONDOWN {
|
2020-05-12 07:11:27 +00:00
|
|
|
return b.Invoke(ctx, b.OnLeftMouseButtonClick)
|
2020-05-10 15:16:18 +00:00
|
|
|
}
|
2020-05-11 06:03:33 +00:00
|
|
|
case *sdl.WindowEvent:
|
|
|
|
if e.Event == sdl.WINDOWEVENT_LEAVE {
|
|
|
|
b.IsMouseOver = false
|
|
|
|
}
|
2020-05-10 15:16:18 +00:00
|
|
|
}
|
2020-05-12 07:11:27 +00:00
|
|
|
return false
|
2020-05-10 15:16:18 +00:00
|
|
|
}
|
|
|
|
|
2020-05-12 07:11:27 +00:00
|
|
|
func (b *ControlBase) Invoke(ctx *Context, fn EventContextFn) bool {
|
2020-05-10 15:16:18 +00:00
|
|
|
if fn == nil {
|
2020-05-12 07:11:27 +00:00
|
|
|
return false
|
2020-05-10 10:21:51 +00:00
|
|
|
}
|
2020-05-10 15:16:18 +00:00
|
|
|
fn(ctx)
|
2020-05-12 07:11:27 +00:00
|
|
|
return true
|
2020-05-10 10:21:51 +00:00
|
|
|
}
|
2020-05-09 13:32:43 +00:00
|
|
|
|
2020-05-10 10:21:51 +00:00
|
|
|
func (b *ControlBase) Render(*Context) {}
|