aboutsummaryrefslogtreecommitdiff
path: root/go/ui/widget.go
blob: f9451a3395b5ca07afe5973a5a338196b5efd4a0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package ui

import (
	"github.com/hajimehoshi/ebiten/v2"
)

type Widget interface {
	Draw(*ebiten.Image)
	FindObjectAt(int, int) any
	Contains(int, int) bool
	Layout() (int, int)

	IsClickable() bool
	Click(int, int)
	IsHoverable() bool
	Hover(bool, int, int)
	IsScrollable() bool
	Scroll(int, int)
	IsUpdatable() bool
	Update() error
	IsFocusable() bool
	Focus(bool)
}

type WidgetBase struct {
	X, Y          int
	Width, Height int
	img           *ebiten.Image
	Op            *ebiten.DrawImageOptions
	renderImpl    func() *ebiten.Image
	EventHandlersMap
}

func NewWidgetBase(x, y, width, height int) WidgetBase {
	return WidgetBase{X: x, Y: y, Width: width, Height: height, Op: &ebiten.DrawImageOptions{}, EventHandlersMap: NewEventHandlersMap()}
}

func (w *WidgetBase) Draw(screen *ebiten.Image) {
	if w.img == nil {
		w.img = w.renderImpl()
	}
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Concat(w.Op.GeoM)
	op.GeoM.Translate(float64(w.X), float64(w.Y))
	screen.DrawImage(w.img, op)
}

func (w *WidgetBase) DrawImageOptions() *ebiten.DrawImageOptions {
	return w.Op
}

func (w *WidgetBase) ForceRedraw() {
	w.img = nil
}

func (w *WidgetBase) Contains(x, y int) bool {
	return x >= 0 && y >= 0 && x >= w.X && x <= w.X+w.Width && y >= w.Y && y <= w.Y+w.Height
}

func (w *WidgetBase) FindObjectAt(int, int) any {
	return nil
}

func (w *WidgetBase) Layout() (int, int) {
	return w.Width, w.Height
}