summaryrefslogtreecommitdiff
path: root/status/00-status.go
blob: dadc668ae3cea07fd020fd967925926518a65b4f (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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package status // import "hhvn.uk/hbspbar/status"

import (
	"fmt"
	"time"
	"image"
	"image/color"

	"hhvn.uk/hbspbar/drw"
	"hhvn.uk/hbspbar/config"
	"hhvn.uk/hbspbar/common"
)

var NewBlocks = make(chan []*Block)
var updates   = make(chan *Block)
var blockid   = make(map[string]int)
var blockids  = 0

type Block struct {
	Name string
	I    *image.RGBA
	W    int
}

func init() {
	blocks := make(map[int]*Block)

	go func() {
		for s := range updates {
			id := blockid[s.Name]

			blocks[id] = s

			b := make([]*Block, blockids)
			for i := 0; i < blockids; i++ {
				b[i] = blocks[i]
			}

			NewBlocks <- b
		}
	}()
}

func register(name string, fn func(string) error) {
	nid := 0
	for _, id := range blockid {
		if id >= nid {
			nid = id + 1
			blockids++
		}
	}
	blockid[name] = nid

	go func(){
		for {
			err := fn(name)

			if err != nil {
				common.Error("block \"%s\": %s\n", name, err)

				u := newUpdate(name)
				u.drawText(0, config.Red, fmt.Sprintf("[err: %s]", name))
				updates <- u

				sleep(5)
			}
		}
	}()
}

func newUpdate(name string) (*Block) {
	var s Block

	s.Name = name
	s.W    = 0
	s.I    = image.NewRGBA(image.Rect(0, 0, 1000, int(config.H)))

	// Use drw's in order not to modify s.W
	drw.DrawRect(s.I, 0, 0, 1000, int(config.H), config.Status, true)

	return &s
}

func sleep(s int) {
	time.Sleep(time.Duration(s) * time.Second)
}

func blendGYR(percent int) color.Color {
	return drw.Blend(percent, config.Green, config.Yellow, config.Red)
}

func blendBg(c color.Color) color.Color {
	return drw.Blend(75, c, config.Status)
}

func (s *Block) furthest(x int) {
	if x > s.W {
		s.W = x
	}
}

func (s *Block) drawText(x int, col color.Color, text string) (int, error) {
	w, err := drw.DrawText(s.I, x, col, text)
	s.furthest(x + w)
	return w, err
}

func (s *Block) drawRect(x, y, w, h int, c color.Color, fill bool) {
	drw.DrawRect(s.I, x, y, w, h, c, fill)
	s.furthest(x + w)
}

func (s *Block) drawPercentBar(x, percent int) int {
	tbpad := 3
	th    := int(config.H) - tbpad * 2 + 1
	h     := int(th * percent / 100)
	fg    := blendGYR(percent)
	bg    := blendBg(fg)

	s.drawRect(x, tbpad - 1, 3, th, bg, true)
	s.drawRect(x, tbpad + th - h - 1, 3, h, fg, true)

	return 5
}