progressbar.go raw

   1  package gel
   2  
   3  import (
   4  	"image"
   5  	"image/color"
   6  
   7  	"github.com/p9c/gio/f32"
   8  	l "github.com/p9c/gio/layout"
   9  	"github.com/p9c/gio/op/clip"
  10  	"github.com/p9c/gio/op/paint"
  11  	"github.com/p9c/gio/unit"
  12  	
  13  	"github.com/p9c/gel/f32color"
  14  )
  15  
  16  type ProgressBar struct {
  17  	*Window
  18  	color    color.NRGBA
  19  	progress int
  20  }
  21  
  22  // ProgressBar renders a horizontal bar with an indication of completion of a process
  23  func (w *Window) ProgressBar() *ProgressBar {
  24  	return &ProgressBar{
  25  		Window:   w,
  26  		progress: 0,
  27  		color:    w.Colors.GetNRGBAFromName("Primary"),
  28  	}
  29  }
  30  
  31  // SetProgress sets the progress of the progress bar
  32  func (p *ProgressBar) SetProgress(progress int) *ProgressBar {
  33  	p.progress = progress
  34  	return p
  35  }
  36  
  37  // Color sets the color to render the bar in
  38  func (p *ProgressBar) Color(c string) *ProgressBar {
  39  	p.color = p.Theme.Colors.GetNRGBAFromName(c)
  40  	return p
  41  }
  42  
  43  // Fn renders the progress bar as it is currently configured
  44  func (p *ProgressBar) Fn(gtx l.Context) l.Dimensions {
  45  	shader := func(width float32, color color.NRGBA) l.Dimensions {
  46  		maxHeight := unit.Dp(4)
  47  		rr := float32(gtx.Px(unit.Dp(2)))
  48  		
  49  		d := image.Point{X: int(width), Y: gtx.Px(maxHeight)}
  50  		
  51  		clip.RRect{
  52  			Rect: f32.Rectangle{Max: f32.Point{X: width, Y: float32(gtx.Px(maxHeight))}},
  53  			NE:   rr, NW: rr, SE: rr, SW: rr,
  54  		}.Add(gtx.Ops)
  55  		
  56  		paint.ColorOp{Color: color}.Add(gtx.Ops)
  57  		paint.PaintOp{}.Add(gtx.Ops)
  58  		
  59  		return l.Dimensions{Size: d}
  60  	}
  61  	
  62  	progress := p.progress
  63  	if progress > 100 {
  64  		progress = 100
  65  	} else if progress < 0 {
  66  		progress = 0
  67  	}
  68  	
  69  	progressBarWidth := float32(gtx.Constraints.Max.X)
  70  	
  71  	return l.Stack{Alignment: l.W}.Layout(gtx,
  72  		l.Stacked(func(gtx l.Context) l.Dimensions {
  73  			// Use a transparent equivalent of progress color.
  74  			bgCol := f32color.MulAlpha(p.color, 150)
  75  			
  76  			return shader(progressBarWidth, bgCol)
  77  		}),
  78  		l.Stacked(func(gtx l.Context) l.Dimensions {
  79  			fillWidth := (progressBarWidth / 100) * float32(progress)
  80  			fillColor := p.color
  81  			if gtx.Queue == nil {
  82  				fillColor = f32color.MulAlpha(fillColor, 200)
  83  			}
  84  			return shader(fillWidth, fillColor)
  85  		}),
  86  	)
  87  }
  88