github.com/TrueBlocks/trueblocks-core/src/apps/chifra@v0.0.0-20241022031540-b362680128f7/pkg/progress/scanbar.go (about) 1 // Copyright 2021 The TrueBlocks Authors. All rights reserved. 2 // Use of this source code is governed by a license that can 3 // be found in the LICENSE file. 4 5 package progress 6 7 import ( 8 "fmt" 9 "io" 10 "strings" 11 "github.com/TrueBlocks/trueblocks-core/src/apps/chifra/pkg/base" 12 ) 13 14 type ScanBar struct { 15 Visited uint64 16 Found uint64 17 Wanted uint64 18 Max uint64 19 Freq uint64 20 WidPct float64 21 } 22 23 func NewScanBar(want, freq, max uint64, widPct float64) *ScanBar { 24 sp := &ScanBar{} 25 sp.Wanted = want 26 sp.Freq = freq 27 if sp.Freq == 0 { 28 sp.Freq = 1 29 } 30 sp.Max = max 31 sp.WidPct = widPct 32 return sp 33 } 34 35 func (v *ScanBar) Satisfied() bool { 36 return v.Visited > v.Max || v.Found == v.Wanted 37 } 38 39 func (v *ScanBar) Pct() float64 { 40 return (float64(v.Visited) / float64(v.Max)) 41 } 42 43 func (v *ScanBar) Report(writer io.Writer, action, msg string) { 44 v.Visited++ 45 if v.Visited%v.Freq != 0 { 46 return 47 } 48 width := int(float64(screenWidth()) * v.WidPct) 49 done := int(float64(width) * v.Pct()) 50 remains := width - done 51 if remains < 0 { 52 remains = 0 53 } 54 w := int(screenWidth()) - 2 55 x := fmt.Sprintf("%s [%s%s] %s", action, strings.Repeat(".", done), strings.Repeat(" ", remains), msg) 56 x = x[0:base.Min(len(x), w)] 57 e := w - len(x) 58 var endPad string = strings.Repeat(" ", e) 59 str := fmt.Sprintf("%s%s\r", x, endPad) 60 _, _ = writer.Write([]byte(str)) 61 } 62 63 type winsize struct { 64 Row uint16 65 Col uint16 66 Xpixel uint16 67 Ypixel uint16 68 }