From 3968b024327a545f02d0177c25e7ac16df34d16b Mon Sep 17 00:00:00 2001 From: Matteo Kloiber Date: Tue, 21 Apr 2015 16:43:09 +0200 Subject: [PATCH] Added support for gauges with custom labels. --- example/gauge.go | 10 +++++++++- gauge.go | 26 ++++++++++++++++---------- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/example/gauge.go b/example/gauge.go index 06e4946..45cc29d 100644 --- a/example/gauge.go +++ b/example/gauge.go @@ -47,7 +47,15 @@ func main() { g1.Border.FgColor = termui.ColorWhite g1.Border.LabelFgColor = termui.ColorMagenta - termui.Render(g0, g1, g2) + g3 := termui.NewGauge() + g3.Percent = 50 + g3.Width = 50 + g3.Height = 3 + g3.Y = 11 + g3.Border.Label = "Gauge with custom label" + g3.Label = "{{percent}}% (100MBs free)" + + termui.Render(g0, g1, g2, g3) <-termui.EventCh() } diff --git a/gauge.go b/gauge.go index 3e0003d..d5abbcd 100644 --- a/gauge.go +++ b/gauge.go @@ -4,7 +4,10 @@ package termui -import "strconv" +import ( + "strconv" + "strings" +) // Gauge is a progress bar like widget. // A simple example: @@ -22,6 +25,7 @@ type Gauge struct { Percent int BarColor Attribute PercentColor Attribute + Label string } // NewGauge return a new gauge with current theme. @@ -29,7 +33,10 @@ func NewGauge() *Gauge { g := &Gauge{ Block: *NewBlock(), PercentColor: theme.GaugePercent, - BarColor: theme.GaugeBar} + BarColor: theme.GaugeBar, + Label: "{{percent}}%", + } + g.Width = 12 g.Height = 5 return g @@ -39,14 +46,8 @@ func NewGauge() *Gauge { func (g *Gauge) Buffer() []Point { ps := g.Block.Buffer() - w := g.Percent * g.innerWidth / 100 - s := strconv.Itoa(g.Percent) + "%" - rs := str2runes(s) - - prx := g.innerX + g.innerWidth/2 - 1 - pry := g.innerY + g.innerHeight/2 - // plot bar + w := g.Percent * g.innerWidth / 100 for i := 0; i < g.innerHeight; i++ { for j := 0; j < w; j++ { p := Point{} @@ -62,13 +63,17 @@ func (g *Gauge) Buffer() []Point { } // plot percentage + s := strings.Replace(g.Label, "{{percent}}", strconv.Itoa(g.Percent), -1) + prx := g.innerX + (g.innerWidth-strWidth(s))/2 + pry := g.innerY + g.innerHeight/2 + rs := str2runes(s) for i, v := range rs { p := Point{} p.X = prx + i p.Y = pry p.Ch = v p.Fg = g.PercentColor - if w > g.innerWidth/2-1+i { + if w > (g.innerWidth-strWidth(s))/2+i { p.Bg = g.BarColor if p.Bg == ColorDefault { p.Bg |= AttrReverse @@ -77,6 +82,7 @@ func (g *Gauge) Buffer() []Point { } else { p.Bg = g.Block.BgColor } + ps = append(ps, p) } return g.Block.chopOverflow(ps)