termui/gauge.go

110 lines
2.2 KiB
Go
Raw Normal View History

2016-01-27 09:45:18 +08:00
// Copyright 2016 Zack Guo <gizak@icloud.com>. All rights reserved.
2015-03-21 04:21:50 +08:00
// Use of this source code is governed by a MIT license that can
// be found in the LICENSE file.
2015-02-04 09:56:49 +08:00
package termui
import (
"strconv"
"strings"
)
2015-02-04 09:56:49 +08:00
2015-03-25 05:16:43 +08: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
*/
2015-10-22 23:17:20 +08:00
const ColorUndef Attribute = Attribute(^uint16(0))
2015-02-04 09:56:49 +08:00
type Gauge struct {
Block
Percent int
BarColor Attribute
PercentColor Attribute
PercentColorHighlighted Attribute
Label string
LabelAlign Align
2015-02-04 09:56:49 +08:00
}
2015-03-25 05:16:43 +08:00
// NewGauge return a new gauge with current theme.
2015-02-04 09:56:49 +08:00
func NewGauge() *Gauge {
g := &Gauge{
Block: *NewBlock(),
2015-10-22 23:17:20 +08:00
PercentColor: ThemeAttr("gauge.percent.fg"),
BarColor: ThemeAttr("gauge.bar.bg"),
Label: "{{percent}}%",
LabelAlign: AlignCenter,
2015-10-22 23:17:20 +08:00
PercentColorHighlighted: ColorUndef,
}
2015-02-04 09:56:49 +08:00
g.Width = 12
g.Height = 5
return g
}
2015-03-25 05:16:43 +08:00
// Buffer implements Bufferer interface.
2015-10-08 02:25:59 +08:00
func (g *Gauge) Buffer() Buffer {
buf := g.Block.Buffer()
2015-02-04 09:56:49 +08:00
// plot bar
2015-10-08 02:25:59 +08:00
w := g.Percent * g.innerArea.Dx() / 100
for i := 0; i < g.innerArea.Dy(); i++ {
2015-02-04 09:56:49 +08:00
for j := 0; j < w; j++ {
2015-10-08 02:25:59 +08:00
c := Cell{}
c.Ch = ' '
c.Bg = g.BarColor
if c.Bg == ColorDefault {
c.Bg |= AttrReverse
}
2015-10-08 02:25:59 +08:00
buf.Set(g.innerArea.Min.X+j, g.innerArea.Min.Y+i, c)
2015-02-04 09:56:49 +08:00
}
}
// plot percentage
s := strings.Replace(g.Label, "{{percent}}", strconv.Itoa(g.Percent), -1)
2015-10-08 02:25:59 +08:00
pry := g.innerArea.Min.Y + g.innerArea.Dy()/2
rs := str2runes(s)
var pos int
switch g.LabelAlign {
case AlignLeft:
pos = 0
case AlignCenter:
2015-10-08 02:25:59 +08:00
pos = (g.innerArea.Dx() - strWidth(s)) / 2
case AlignRight:
2015-10-10 23:20:44 +08:00
pos = g.innerArea.Dx() - strWidth(s) - 1
}
2015-10-10 23:20:44 +08:00
pos += g.innerArea.Min.X
2015-02-04 09:56:49 +08:00
for i, v := range rs {
2015-10-08 02:25:59 +08:00
c := Cell{
Ch: v,
Fg: g.PercentColor,
}
if w+g.innerArea.Min.X > pos+i {
c.Bg = g.BarColor
if c.Bg == ColorDefault {
c.Bg |= AttrReverse
}
2015-10-22 23:17:20 +08:00
if g.PercentColorHighlighted != ColorUndef {
c.Fg = g.PercentColorHighlighted
}
2015-02-04 09:56:49 +08:00
} else {
2015-10-08 02:25:59 +08:00
c.Bg = g.Block.Bg
2015-02-04 09:56:49 +08:00
}
2015-10-08 02:25:59 +08:00
buf.Set(1+pos+i, pry, c)
2015-02-04 09:56:49 +08:00
}
2015-10-08 02:25:59 +08:00
return buf
2015-02-04 09:56:49 +08:00
}