diff --git a/_examples/marqueeDecorator/go.mod b/_examples/marqueeDecorator/go.mod new file mode 100644 index 00000000..e8d159b8 --- /dev/null +++ b/_examples/marqueeDecorator/go.mod @@ -0,0 +1,13 @@ +module github.com/vbauerster/mpb/_examples/marqueeDecorator + +go 1.17 + +require github.com/vbauerster/mpb/v8 v8.3.0 + +require ( + github.com/VividCortex/ewma v1.2.0 // indirect + github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect + github.com/mattn/go-runewidth v0.0.14 // indirect + github.com/rivo/uniseg v0.4.4 // indirect + golang.org/x/sys v0.6.0 // indirect +) diff --git a/_examples/marqueeDecorator/main.go b/_examples/marqueeDecorator/main.go new file mode 100644 index 00000000..e50d1c28 --- /dev/null +++ b/_examples/marqueeDecorator/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" + "math/rand" + "sync" + "time" + + "github.com/vbauerster/mpb/v8" + "github.com/vbauerster/mpb/v8/decor" +) + +func main() { + var wg sync.WaitGroup + // passed wg will be accounted at p.Wait() call + p := mpb.New(mpb.WithWaitGroup(&wg), mpb.WithWidth(64)) + total, numBars := 100, 3 + wg.Add(numBars) + + fileToDownload := []string{ + "One Hundred Years of Solitude by Gabriel Garcia Marquez", + "The Brothers Karamazov by Fyodor Dostoyevsky", + "Alice's Adventures in Wonderland by Lewis Carroll", + } + + for i := 0; i < numBars; i++ { + name := fmt.Sprintf("Bar#%d:", i) + bar := p.AddBar(int64(total), + mpb.PrependDecorators( + // simple name decorator + decor.Name(name), + decor.OnComplete( + // Marquee decorator with default style + Marquee(fileToDownload[i], 20, decor.WCSyncSpace), "done", + ), + ), + mpb.AppendDecorators( + // decor.DSyncWidth bit enables column width synchronization + decor.Percentage(decor.WCSyncWidth), + ), + ) + // simulating some work + go func() { + defer wg.Done() + rng := rand.New(rand.NewSource(time.Now().UnixNano())) + max := 100 * time.Millisecond + for i := 0; i < total; i++ { + time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) + bar.Increment() + } + }() + } + // wait for passed wg and for all bars to complete and flush + p.Wait() +} diff --git a/decor/marquee.go b/decor/marquee.go new file mode 100644 index 00000000..c319fb20 --- /dev/null +++ b/decor/marquee.go @@ -0,0 +1,25 @@ +package decor + +// Marquee returns marquee decorator that will scroll text right to left. +// +// `text` is the scrolling message +// +// `ws` controls the showing window size +func Marquee(text string, ws uint, wcc ...WC) Decorator { + bytes := []byte(text) + buf := make([]byte, ws) + var count uint + f := func(s Statistics) string { + start := count % uint(len(bytes)) + var i uint = 0 + for ; i < ws && start+i < uint(len(bytes)); i++ { + buf[i] = bytes[start+i] + } + for ; i < ws; i++ { + buf[i] = ' ' + } + count++ + return string(buf) + } + return Any(f, wcc...) +}