xmtop/termui/gauge.go

55 lines
968 B
Go
Raw Normal View History

2018-02-18 23:25:02 -08:00
package termui
2018-02-18 23:51:55 -08:00
import (
"strconv"
)
2018-02-18 23:25:02 -08:00
// Gauge is a progress bar like widget.
type Gauge struct {
*Block
Percent int
2018-02-21 00:46:11 -08:00
BarColor Color
PercentColor Color
2018-02-18 23:25:02 -08:00
Description string
}
// NewGauge return a new gauge with current theme.
func NewGauge() *Gauge {
return &Gauge{
Block: NewBlock(),
PercentColor: Theme.Fg,
2018-02-21 02:24:36 -08:00
BarColor: Theme.BarColor,
2018-02-18 23:25:02 -08:00
}
}
// 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++ {
2018-02-21 02:24:36 -08:00
buf.SetCell(x, y, Cell{' ', g.BarColor, g.BarColor})
2018-02-18 23:25:02 -08:00
}
}
// 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
2018-02-21 02:24:36 -08:00
fg := g.Fg
2018-02-18 23:25:02 -08:00
if x+i < width {
2018-02-21 02:24:36 -08:00
fg = g.BarColor
2018-02-18 23:25:02 -08:00
bg = AttrReverse
}
2018-02-21 02:24:36 -08:00
buf.SetCell(1+x+i, y, Cell{char, fg, bg})
2018-02-18 23:25:02 -08:00
}
return buf
}