termui/gauge.go

122 lines
2.4 KiB
Go
Raw Normal View History

2015-03-20 20:21:50 +00:00
// Copyright 2015 Zack Guo <gizak@icloud.com>. All rights reserved.
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
2015-02-04 01:56:49 +00:00
package termui
import (
"strconv"
"strings"
)
2015-02-04 01:56:49 +00:00
2015-03-24 21:16:43 +00:00
// Gauge is a progress bar like widget.
// A simple example:
/*
g := termui.NewGauge()
g.Percent = 40
g.Width = 50
g.Height = 3
g.Border.Label = "Slim Gauge"
g.BarColor = termui.ColorRed
g.PercentColor = termui.ColorBlue
*/
// Align is the position of the gauge's label.
type Align int
// All supported positions.
const (
AlignLeft Align = iota
AlignCenter
AlignRight
)
const uint16max = ^uint16(0)
2015-02-04 01:56:49 +00:00
type Gauge struct {
Block
Percent int
BarColor Attribute
PercentColor Attribute
PercentColorHighlighted Attribute
Label string
LabelAlign Align
2015-02-04 01:56:49 +00:00
}
2015-03-24 21:16:43 +00:00
// NewGauge return a new gauge with current theme.
2015-02-04 01:56:49 +00:00
func NewGauge() *Gauge {
g := &Gauge{
Block: *NewBlock(),
PercentColor: theme.GaugePercent,
BarColor: theme.GaugeBar,
Label: "{{percent}}%",
LabelAlign: AlignCenter,
PercentColorHighlighted: Attribute(uint16max),
}
2015-02-04 01:56:49 +00:00
g.Width = 12
g.Height = 5
return g
}
2015-03-24 21:16:43 +00:00
// Buffer implements Bufferer interface.
2015-02-04 01:56:49 +00:00
func (g *Gauge) Buffer() []Point {
ps := g.Block.Buffer()
// plot bar
w := g.Percent * g.innerWidth / 100
2015-02-04 01:56:49 +00:00
for i := 0; i < g.innerHeight; i++ {
for j := 0; j < w; j++ {
p := Point{}
p.X = g.innerX + j
p.Y = g.innerY + i
2015-03-03 18:28:09 +00:00
p.Ch = ' '
p.Bg = g.BarColor
if p.Bg == ColorDefault {
p.Bg |= AttrReverse
}
2015-02-04 01:56:49 +00:00
ps = append(ps, p)
}
}
// plot percentage
s := strings.Replace(g.Label, "{{percent}}", strconv.Itoa(g.Percent), -1)
pry := g.innerY + g.innerHeight/2
rs := str2runes(s)
var pos int
switch g.LabelAlign {
case AlignLeft:
pos = 0
case AlignCenter:
pos = (g.innerWidth - strWidth(s)) / 2
case AlignRight:
pos = g.innerWidth - strWidth(s)
}
2015-08-29 21:05:24 +00:00
pos += g.innerX
2015-02-04 01:56:49 +00:00
for i, v := range rs {
p := Point{}
p.X = 1 + pos + i
2015-02-04 01:56:49 +00:00
p.Y = pry
2015-03-03 18:28:09 +00:00
p.Ch = v
p.Fg = g.PercentColor
if w+g.innerX > pos+i {
2015-03-03 18:28:09 +00:00
p.Bg = g.BarColor
if p.Bg == ColorDefault {
p.Bg |= AttrReverse
}
if g.PercentColorHighlighted != Attribute(uint16max) {
p.Fg = g.PercentColorHighlighted
}
2015-02-04 01:56:49 +00:00
} else {
2015-03-03 18:28:09 +00:00
p.Bg = g.Block.BgColor
2015-02-04 01:56:49 +00:00
}
2015-02-04 01:56:49 +00:00
ps = append(ps, p)
}
return g.Block.chopOverflow(ps)
2015-02-04 01:56:49 +00:00
}