forked from quantum/gonsole
-
Notifications
You must be signed in to change notification settings - Fork 0
/
progress.go
61 lines (46 loc) · 1.25 KB
/
progress.go
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
55
56
57
58
59
60
61
package gonsole
import (
"fmt"
"strings"
xs "github.com/huandu/xstrings"
)
type Progress struct {
BaseControl
// a value between 0 and 1
value float32
}
func NewProgress(win *Window, parent Container, id string) *Progress {
p := &Progress{}
p.Init(win, parent, id, "progress")
parent.AddControl(p)
return p
}
func (p *Progress) Value() float32 {
return p.value
}
func (p *Progress) SetValue(value float32) {
cb := p.ContentBox()
currentPercent := int(p.value * float32(cb.Width))
newPercent := int(value * float32(cb.Width))
p.value = value
if p.value > 1 {
p.value = 1
}
if currentPercent != newPercent {
p.window.App().Redraw()
}
}
func (p *Progress) Repaint() {
if !p.Dirty() {
return
}
p.BaseControl.Repaint()
cb := p.ContentBox()
text := strings.Repeat(" ", (cb.Width/2)-1)
text += fmt.Sprintf("%d%%", int(p.value*100))
text += strings.Repeat(" ", cb.Width-xs.Len(text))
t := p.Theme()
percent := int(p.value * float32(cb.Width))
DrawTextSimple(xs.Slice(text, 0, percent), false, p.ContentBox(), t.ColorTermbox("filled.fg"), t.ColorTermbox("filled.bg"))
DrawTextSimple(xs.Slice(text, percent, -1), false, Box{cb.Left + percent, cb.Top, cb.Width - percent, cb.Height}, t.ColorTermbox("empty.fg"), t.ColorTermbox("empty.bg"))
}