aboutsummaryrefslogtreecommitdiffstats
path: root/gui/widget/focus.go
blob: f1bc06e42a3f5274f6a90ab6fac95e5673d7e28e (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
86
87
88
89
90
91
92
93
94
95
96
97
98
package widget

import (
	"image"
	"sync"
)

type FocusMaster struct {
	slaves [][]chan bool
	mu     sync.Mutex
	p      image.Point // coordinates of currently focused slave
}

type FocusSlave struct {
	Focus <-chan bool
	Mu    *sync.Mutex
}

func NewFocusMaster(rows []int) FocusMaster {
	f := FocusMaster{
		make([][]chan bool, len(rows)),
		sync.Mutex{},
		image.Point{},
	}
	for i := range f.slaves {
		f.slaves[i] = make([]chan bool, rows[i])
		for j := range f.slaves[i] {
			f.slaves[i][j] = make(chan bool)
		}
	}
	return f
}

func (f *FocusMaster) Slave(y, x int) FocusSlave {
	return FocusSlave{f.slaves[y][x], &f.mu}
}

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

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

func (f *FocusMaster) TryLeft() {
	if !f.mu.TryLock() {
		return
	}
	defer f.mu.Unlock()
	f.Focus(false)
	if f.p.X <= 0 {
		f.p.X = len(f.slaves[f.p.Y]) - 1
	} else {
		f.p.X--
	}
	f.Focus(true)
}

func (f *FocusMaster) TryRight() {
	if !f.mu.TryLock() {
		return
	}
	defer f.mu.Unlock()
	f.Focus(false)
	f.p.X = (f.p.X + 1) % len(f.slaves[f.p.Y])
	f.Focus(true)
}

func (f *FocusMaster) TryUp() {
	if !f.mu.TryLock() {
		return
	}
	defer f.mu.Unlock()
	f.Focus(false)
	if f.p.Y <= 0 {
		f.p.Y = len(f.slaves) - 1
	} else {
		f.p.Y--
	}
	f.p.X = min(f.p.X, len(f.slaves[f.p.Y])-1)
	f.Focus(true)
}

func (f *FocusMaster) TryDown() {
	if !f.mu.TryLock() {
		return
	}
	defer f.mu.Unlock()
	f.Focus(false)
	f.p.Y = (f.p.Y + 1) % len(f.slaves)
	f.p.X = min(f.p.X, len(f.slaves[f.p.Y])-1)
	f.Focus(true)
}