summaryrefslogtreecommitdiffstats
path: root/termui/gauge.go
blob: 7e6ab7ecd47e7bb3b07018c33672fb6b7a16089e (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
package termui

import (
	"strconv"
)

// Gauge is a progress bar like widget.
type Gauge struct {
	*Block
	Percent      int
	BarColor     Color
	PercentColor Color
	Description  string
}

// NewGauge return a new gauge with current theme.
func NewGauge() *Gauge {
	return &Gauge{
		Block:        NewBlock(),
		PercentColor: Theme.Fg,
		BarColor:     Theme.BarColor,
	}
}

// Buffer implements Bufferer interface.
func (g *Gauge) Buffer() *Buffer {
	buf := g.Block.Buffer()

	// plot bar
	width := g.Percent * g.X / 100
	for y := 1; y <= g.Y; y++ {
		for x := 1; x <= width; x++ {
			buf.SetCell(x, y, Cell{' ', g.BarColor, g.BarColor})
		}
	}

	// plot percentage
	s := strconv.Itoa(g.Percent) + "%" + g.Description
	y := (g.Y + 1) / 2
	s = MaxString(s, g.X)
	x := ((g.X - len(s)) + 1) / 2

	for i, char := range s {
		bg := g.Bg
		fg := g.Fg
		if x+i < width {
			fg = g.BarColor
			bg = AttrReverse
		}
		buf.SetCell(1+x+i, y, Cell{char, fg, bg})
	}

	return buf
}