fork/gdu

git clone https://git.julia.blue/fork/gdu

Daniel Mildefeat: show progress bar when analysing the whole disk/partition (#523)8f80d99

ignore
2.4 KiB107 linesraw
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
17	progress int // 0–100
18	useColor bool
19
20	mu sync.RWMutex
21}
22
23// NewProgressBar returns a new ProgressBar with default settings.
24func NewProgressBar() *ProgressBar {
25	return &ProgressBar{
26		Box: tview.NewBox(),
27	}
28}
29
30// SetUseColor controls whether the filled segment is highlighted with colour.
31func (p *ProgressBar) SetUseColor(use bool) *ProgressBar {
32	p.mu.Lock()
33	defer p.mu.Unlock()
34	p.useColor = use
35	return p
36}
37
38// SetProgress sets the current progress in the range [0, 100].
39func (p *ProgressBar) SetProgress(progress int) {
40	p.mu.Lock()
41	defer p.mu.Unlock()
42	if progress < 0 {
43		progress = 0
44	} else if progress > 100 {
45		progress = 100
46	}
47	p.progress = progress
48}
49
50// GetProgress returns the current progress in the range [0, 100].
51func (p *ProgressBar) GetProgress() int {
52	p.mu.RLock()
53	defer p.mu.RUnlock()
54	return 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) {
60	p.Box.Draw(screen)
61
62	p.mu.RLock()
63	progress := p.progress
64	useColor := p.useColor
65	p.mu.RUnlock()
66
67	x, y, width, height := p.GetInnerRect()
68	if width <= 0 || height <= 0 {
69		return
70	}
71
72	percentStr := fmt.Sprintf(" %3d%% ", progress)
73	barWidth := width - len(percentStr)
74	if barWidth < 0 {
75		barWidth = 0
76	}
77
78	filled := 0
79	if barWidth > 0 && progress > 0 {
80		filled = barWidth * progress / 100
81	}
82
83	filledStyle := tcell.StyleDefault.Foreground(tcell.ColorDefault)
84	if useColor {
85		filledStyle = tcell.StyleDefault.Foreground(tcell.ColorGreen)
86	}
87	emptyStyle := tcell.StyleDefault.Foreground(tcell.ColorGray)
88	textStyle := tcell.StyleDefault.Foreground(tcell.ColorDefault)
89
90	// Render only the middle row; if height > 1 the box padding handles spacing.
91	row := (height - 1) / 2
92	for col := 0; col < barWidth; col++ {
93		ch := '░'
94		style := emptyStyle
95		if col < filled {
96			ch = '█'
97			style = filledStyle
98		}
99		screen.SetContent(x+col, y+row, ch, nil, style)
100	}
101	for i, ch := range []rune(percentStr) {
102		if barWidth+i >= width {
103			break
104		}
105		screen.SetContent(x+barWidth+i, y+row, ch, nil, textStyle)
106	}
107}