aboutsummaryrefslogtreecommitdiffstats
path: root/gui/widget/focus.go
blob: e2d1074eca9d78bbfd367425034324fc322374a5 (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
package widget

import "image"

// Focus keeps track of the currently selected widget.
// A widget receives true when it gains focus and false when it loses focus.
type Focus struct {
	Widgets [][]chan bool
	p       image.Point // coordinates of currently focused widget
}

func NewFocus(rows []int) Focus {
	f := Focus{
		make([][]chan bool, len(rows)),
		image.Point{},
	}
	for i := range f.Widgets {
		f.Widgets[i] = make([]chan bool, rows[i])
		for j := range f.Widgets[i] {
			f.Widgets[i][j] = make(chan bool)
		}
	}
	return f
}

func (f *Focus) Close() {
	for i := range f.Widgets {
		for j := range f.Widgets[i] {
			close(f.Widgets[i][j])
		}
	}
}

func (f *Focus) Focus(focus bool) {
	f.Widgets[f.p.Y][f.p.X] <- focus
}

func (f *Focus) Left() {
	f.Focus(false)
	if f.p.X <= 0 {
		f.p.X = len(f.Widgets[f.p.Y]) - 1
	} else {
		f.p.X--
	}
	f.Focus(true)
}

func (f *Focus) Right() {
	f.Focus(false)
	f.p.X = (f.p.X + 1) % len(f.Widgets[f.p.Y])
	f.Focus(true)
}

func (f *Focus) Up() {
	f.Focus(false)
	if f.p.Y <= 0 {
		f.p.Y = len(f.Widgets) - 1
	} else {
		f.p.Y--
	}
	f.p.X = min(f.p.X, len(f.Widgets[f.p.Y])-1)
	f.Focus(true)
}

func (f *Focus) Down() {
	f.Focus(false)
	f.p.Y = (f.p.Y + 1) % len(f.Widgets)
	f.p.X = min(f.p.X, len(f.Widgets[f.p.Y])-1)
	f.Focus(true)
}