build: PKGBUILD added
[zvuchno.git] / volume_bar.go
1 // This file is a part of git.thekondor.net/zvuchno.git (mirror: github.com/thekondor/zvuchno)
2
3 package main
4
5 import (
6         "bytes"
7         "fmt"
8         "github.com/cheggaaa/pb"
9         "log"
10         "text/template"
11 )
12
13 type VolumeBar struct {
14         progressBar *pb.ProgressBar
15         tpl         *template.Template
16 }
17
18 func NewVolumeBar(width byte, formatTpl, barFormat string) VolumeBar {
19         bar := pb.New(100)
20         bar.ManualUpdate = true
21         bar.ShowCounters = false
22         bar.ShowTimeLeft = false
23         bar.ShowFinalTime = false
24         bar.ShowPercent = false
25         bar.SetWidth(int(width))
26         bar.Format(barFormat)
27
28         return VolumeBar{bar, template.Must(template.New("full format").Parse(formatTpl))}
29 }
30
31 func (vb VolumeBar) Update(value int) string {
32         percent := value / 655
33         vb.progressBar.Set(percent)
34         vb.progressBar.Update()
35
36         return vb.toString(percent)
37 }
38
39 func (vb VolumeBar) toString(percent int) string {
40         var output bytes.Buffer
41
42         progress := vb.progressBar.String()
43         if err := vb.tpl.Execute(&output, struct {
44                 Percent int
45                 Bar     string
46         }{percent, progress}); nil != err {
47                 log.Printf("W: template formatting error = %s", err)
48                 return fmt.Sprintf("(fallback): %d%% %s", percent, progress)
49         }
50
51         return output.String()
52 }