Codebase list golang-github-vbauerster-mpb / f74e95b
incorrent current update fix Vladimir Bauer 9 years ago
1 changed file(s) with 26 addition(s) and 21 deletion(s). Raw diff Collapse all Expand all
2626
2727 // Bar represents a progress bar
2828 type Bar struct {
29 // Total of the total for the progress bar
30 Total int
29 // total of the total for the progress bar
30 total int
3131
3232 // LeftEnd is character in the left most part of the progress indicator. Defaults to '['
3333 LeftEnd byte
4949
5050 currentUpdateCh chan int
5151
52 redrawRequestCh chan redrawRequest
52 redrawRequestCh chan *redrawRequest
5353
5454 // appendFuncs []DecoratorFunc
5555 // prependFuncs []DecoratorFunc
6161 // NewBar returns a new progress bar
6262 func NewBar(total int) *Bar {
6363 b := &Bar{
64 Total: total,
64 total: total,
6565 Width: Width,
6666 LeftEnd: LeftEnd,
6767 RightEnd: RightEnd,
6969 Fill: Fill,
7070 Empty: Empty,
7171 currentUpdateCh: make(chan int),
72 redrawRequestCh: make(chan redrawRequest),
72 redrawRequestCh: make(chan *redrawRequest),
7373 }
7474 go b.server()
7575 return b
7777
7878 type redrawRequest struct {
7979 bufch chan []byte
80 }
81
82 func (b *Bar) Update(n int) {
83 b.currentUpdateCh <- n
84 }
85
86 // String returns the string representation of the bar
87 func (b *Bar) String() string {
88 bufch := make(chan []byte)
89 b.redrawRequestCh <- &redrawRequest{bufch}
90 return string(<-bufch)
8091 }
8192
8293 func (b *Bar) server() {
8798 for {
8899 select {
89100 case n := <-b.currentUpdateCh:
90 current += n
101 if n > b.total {
102 return
103 }
104 current = n
105 // fmt.Printf("current = %+v\n", current)
91106 // blockStartTime = time.Now()
92107 case r := <-b.redrawRequestCh:
93 r.bufch <- b.buffer(current)
108 r.bufch <- b.draw(current)
94109 }
95110 }
96111 }
97112
98 func (b *Bar) Update(n int) {
99 b.currentUpdateCh <- n
100 }
101
102 func (b *Bar) buffer(current int) []byte {
103 completedPercent := int(100 * float64(current) / float64(b.Total))
104 completedWidth := completedPercent * b.Width / 100
113 func (b *Bar) draw(current int) []byte {
114 completedWidth := current * b.Width / b.total
105115
106116 // add fill and empty bits
107117 var buf bytes.Buffer
118 // buf.WriteString(fmt.Sprintf("completedWidth = %+v ", completedWidth))
119 // buf.WriteString(fmt.Sprintf("current = %+v ", current))
108120 for i := 0; i < completedWidth; i++ {
109121 buf.WriteByte(b.Fill)
110122 }
134146 // pb = append(args, pb...)
135147 // }
136148 return pb
137 }
138
139 // String returns the string representation of the bar
140 func (b *Bar) String() string {
141 bufch := make(chan []byte)
142 b.redrawRequestCh <- redrawRequest{bufch}
143 return string(<-bufch)
144149 }
145150
146151 // CompletedPercent return the percent completed