aboutsummaryrefslogtreecommitdiffstats
path: root/gui/widget/input.go
blob: f47f587a6b00d21b6b7b9b6c55009f6990ae6a7e (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package widget

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

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

func Input(val chan<- uint, r image.Rectangle, focus FocusSlave, env gui.Env, wg *sync.WaitGroup) {
	defer wg.Done()
	defer close(env.Draw())
	defer close(val)

	text := []byte{'0'}
	focused := false
	env.Draw() <- inputDraw(text, focused, r)
Loop:
	for {
		select {
		case _, ok := <-focus.gain:
			if !ok {
				break Loop
			}
			focused = true
			env.Draw() <- inputDraw(text, focused, r)
		case dir, ok := <-focus.lose:
			if !ok {
				break Loop
			}
			focus.yield <- dir
			focused = false
			env.Draw() <- inputDraw(text, focused, r)
		case event, ok := <-env.Events():
			if !ok {
				break Loop
			}
			switch event := event.(type) {
			case win.WiFocus:
				if event.Focused {
					env.Draw() <- inputDraw(text, focused, r)
				}
			case win.KbType:
				if focused && isDigit(event.Rune) {
					text = fmt.Appendf(text, "%c", event.Rune)
					env.Draw() <- inputDraw(text, focused, r)
					val <- atoi(text)
				}
			case win.KbDown:
				if focused && event.Key == win.KeyBackspace && len(text) > 0 {
					text = text[:len(text)-1]
					env.Draw() <- inputDraw(text, focused, r)
					val <- atoi(text)
				}
			}
		}
	}
}

func inputDraw(str []byte, focused bool, r image.Rectangle) func(draw.Image) image.Rectangle {
	return func(drw draw.Image) image.Rectangle {
		if focused {
			text.Draw(str, drw, r, GREEN, FOCUS_COLOR, text.ALIGN_RIGHT)
		} else {
			text.Draw(str, drw, r, GREEN, WHITE, text.ALIGN_RIGHT)
		}
		return r
	}
}

func isDigit(r rune) bool {
	return '0' <= r && r <= '9'
}

func atoi(s []byte) uint {
	var n uint = 0
	for _, d := range s {
		n = n*10 + uint(d-'0')
	}
	return n
}