fork/gdu
git clone https://git.julia.blue/fork/gdu
8f80d99
master
1package tui 2 3import ( 4"fmt" 5"sync" 6 7"github.com/gdamore/tcell/v2" 8"github.com/rivo/tview" 9) 10 11// ProgressBar is a tview primitive that renders a horizontal progress bar. 12// It embeds tview.Box so it participates in layout and can optionally have 13// a border and title. 14type ProgressBar struct { 15* tview.Box 16 17progress int // 0–100 18useColor bool 19 20mu sync.RWMutex 21} 22 23// NewProgressBar returns a new ProgressBar with default settings. 24func NewProgressBar ()* ProgressBar { 25return & ProgressBar { 26Box :tview .NewBox (), 27 } 28} 29 30// SetUseColor controls whether the filled segment is highlighted with colour. 31func (p * ProgressBar )SetUseColor (use bool )* ProgressBar { 32p .mu .Lock () 33defer p .mu .Unlock () 34p .useColor = use 35return p 36} 37 38// SetProgress sets the current progress in the range [0, 100]. 39func (p * ProgressBar )SetProgress (progress int ) { 40p .mu .Lock () 41defer p .mu .Unlock () 42if progress < 0 { 43progress = 0 44 }else if progress > 100 { 45progress = 100 46 } 47p .progress = progress 48} 49 50// GetProgress returns the current progress in the range [0, 100]. 51func (p * ProgressBar )GetProgress ()int { 52p .mu .RLock () 53defer p .mu .RUnlock () 54return p .progress 55} 56 57// Draw implements tview.Primitive. It draws the border (via Box.Draw) and 58// then fills the inner rect with a segmented progress bar. 59func (p * ProgressBar )Draw (screen tcell.Screen ) { 60p .Box .Draw (screen ) 61 62p .mu .RLock () 63progress := p .progress 64useColor := p .useColor 65p .mu .RUnlock () 66 67x ,y ,width ,height := p .GetInnerRect () 68if width <= 0 || height <= 0 { 69return 70 } 71 72percentStr := fmt .Sprintf (" %3d%% " ,progress ) 73barWidth := width - len (percentStr ) 74if barWidth < 0 { 75barWidth = 0 76 } 77 78filled := 0 79if barWidth > 0 && progress > 0 { 80filled = barWidth * progress / 100 81 } 82 83filledStyle := tcell .StyleDefault .Foreground (tcell .ColorDefault ) 84if useColor { 85filledStyle = tcell .StyleDefault .Foreground (tcell .ColorGreen ) 86 } 87emptyStyle := tcell .StyleDefault .Foreground (tcell .ColorGray ) 88textStyle := tcell .StyleDefault .Foreground (tcell .ColorDefault ) 89 90// Render only the middle row; if height > 1 the box padding handles spacing. 91row := (height - 1 )/ 2 92for col := 0 ;col < barWidth ;col ++ { 93ch := '░' 94style := emptyStyle 95if col < filled { 96ch = '█' 97style = filledStyle 98 } 99screen .SetContent (x + col ,y + row ,ch ,nil ,style ) 100 } 101for i ,ch := range []rune (percentStr ) { 102if barWidth + i >= width { 103break 104 } 105screen .SetContent (x + barWidth + i ,y + row ,ch ,nil ,textStyle ) 106 } 107}