Debian Codegraph @

progress.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // mauview - A Go TUI library based on tcell.
2 // Copyright © 2020 Tulir Asokan
3 //
4 // This Source Code Form is subject to the terms of the Mozilla Public
5 // License, v. 2.0. If a copy of the MPL was not distributed with this
6 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
7
8 package mauview
9
10 import (
11 "math"
12 "sync/atomic"
13 "time"
14
•15 "github.com/gdamore/tcell/v2"
16 )
17
18 type ProgressBar struct {
19 *SimpleEventHandler
20 style tcell.Style
21 progress int32
22 max int
23
24 indeterminate bool
25 indeterminateStart time.Time
26 }
27
28 var _ Component = &ProgressBar{}
29
30 func NewProgressBar() *ProgressBar {
31 return &ProgressBar{
32 SimpleEventHandler: &SimpleEventHandler{},
33
34 style: tcell.StyleDefault,
35 progress: 0,
36 max: 100,
37 indeterminate: true,
38 }
39 }
40
41 var Blocks = [9]rune{' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'}
42
43 func min(a, b int) int {
44 if a < b {
45 return a
46 }
47 return b
48 }
49
50 func (pb *ProgressBar) SetProgress(progress int) *ProgressBar {
51 pb.progress = int32(min(progress, pb.max))
52 return pb
53 }
54
55 func (pb *ProgressBar) Increment(increment int) *ProgressBar {
56 atomic.AddInt32(&pb.progress, int32(increment))
57 return pb
58 }
59
60 func (pb *ProgressBar) SetIndeterminate(indeterminate bool) *ProgressBar {
61 pb.indeterminate = indeterminate
62 pb.indeterminateStart = time.Now()
63 return pb
64 }
65
66 func (pb *ProgressBar) SetMax(max int) *ProgressBar {
67 pb.max = max
68 pb.progress = int32(min(pb.max, int(pb.progress)))
69 return pb
70 }
71
72 // Draw draws this primitive onto the screen.
73 func (pb *ProgressBar) Draw(screen Screen) {
74 width, _ := screen.Size()
75 if pb.indeterminate {
76 barWidth := width / 6
77 pos := int(time.Now().Sub(pb.indeterminateStart).Milliseconds()/200) % (width + barWidth)
78 for x := pos - barWidth; x < pos; x++ {
79 screen.SetCell(x, 0, pb.style, Blocks[8])
80 }
81 } else {
82 progress := math.Min(float64(pb.progress), float64(pb.max))
83 floatingBlocks := progress * (float64(width) / float64(pb.max))
84 parts := int(math.Floor(math.Mod(floatingBlocks, 1) * 8))
85 blocks := int(math.Floor(floatingBlocks))
86 for x := 0; x < blocks; x++ {
87 screen.SetCell(x, 0, pb.style, Blocks[8])
88 }
89 screen.SetCell(blocks, 0, pb.style, Blocks[parts])
90 }
91 }