aboutsummaryrefslogtreecommitdiffstats
path: root/gui/widget/button.go
blob: 4ef5ef427fea99b688a445f7d3da3988fd2afab1 (plain) (blame)
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
package widget

import (
	"image"
	"image/draw"
	"sync"

	"volute/gui"
	"volute/gui/text"
	"volute/gui/win"
)

// Sends signal over tx when Enter is pressed while focused.
func Button[T any](
	tx chan<- T,
	signal T,
	label string,
	r image.Rectangle,
	focus FocusSlave,
	env gui.Env,
	wg *sync.WaitGroup,
) {
	defer wg.Done()
	defer close(tx)

	focused := false
	env.Draw() <- buttonDraw(label, focused, r)
	for {
		select {
		case _, ok := <-focus.gain:
			if !ok {
				return
			}
			focused = true
			env.Draw() <- buttonDraw(label, focused, r)
		case dir, ok := <-focus.lose:
			if !ok {
				return
			}
			focus.yield <- dir
			focused = false
			env.Draw() <- buttonDraw(label, focused, r)
		case event, ok := <-env.Events():
			if !ok {
				return
			}
			if event, ok := event.(win.KbDown); ok && focused && event.Key == win.KeyEnter {
				tx <- signal
			}
		}
	}
}

func buttonDraw(label string, focused bool, r image.Rectangle) func(drw draw.Image) image.Rectangle {
	return func(drw draw.Image) image.Rectangle {
		if focused {
			text.Draw(label, drw, r, BLACK, FOCUS_COLOR, text.ALIGN_LEFT)
		} else {
			text.Draw(label, drw, r, BLACK, WHITE, text.ALIGN_LEFT)
		}
		return r
	}
}