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 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
package loading
import (
"fmt"
"sync"
"github.com/liamg/tml"
"github.com/liamg/clinch/terminal"
)
type Bar struct {
lock sync.Mutex
complete bool
}
// NewBar creates a new loading bar
func NewBar() *Bar {
return &Bar{}
}
// SetPercent sets the current percentage completion of the bar, and renders it to the current line
func (bar *Bar) SetPercent(percent float64) {
bar.lock.Lock()
defer bar.lock.Unlock()
if bar.complete {
return
}
w, h := terminal.Size()
terminal.HideCursor()
terminal.MoveCursorTo(0, h-1)
if percent > 100 {
percent = 100
} else if percent < 0 {
percent = 0
}
barWidth := w - 5
size := int(percent * float64(barWidth) / 100)
remaining := int((100 - percent) * float64(barWidth) / 100)
terminal.ClearLine()
for i := 0; i < size; i++ {
tml.Printf("<bg-blue> </bg-blue>")
}
for remaining > 0 {
fmt.Printf(" ")
remaining--
}
fmt.Printf(" %d%%", int(percent))
}
// Log logs a messages to the terminal without disrupting the rendered loading bar
func (bar *Bar) Log(msg string) {
bar.lock.Lock()
defer bar.lock.Unlock()
terminal.ClearLine()
fmt.Println(msg)
}
// Close hides the loading bar and tidies up
func (bar *Bar) Close() {
bar.lock.Lock()
defer bar.lock.Unlock()
bar.complete = true
_, h := terminal.Size()
terminal.MoveCursorTo(0, h-1)
terminal.ClearLine()
terminal.ShowCursor()
}
|