aerc/widgets/spinner.go
Simon Ser 5685a17674 lib/ui: introduce Invalidatable
Many Drawable implementations have their own Invalidate and OnInvalidate
functions, with an unexported onInvalidate field. However OnInvalidate and
Invalidate are usually not called in the same goroutine. This results in a race
on this field, e.g.:

    Read at 0x00c000094748 by goroutine 7:
      git.sr.ht/~sircmpwn/aerc2/widgets.NewDirectoryList.func1()
          /home/simon/src/aerc2/widgets/dirlist.go:85 +0x56
      git.sr.ht/~sircmpwn/aerc2/widgets.(*Spinner).Start.func1()
          /home/simon/src/aerc2/widgets/spinner.go:93 +0x1bb

    Previous write at 0x00c000094748 by main goroutine:
      [failed to restore the stack]

    Goroutine 7 (running) created at:
      git.sr.ht/~sircmpwn/aerc2/widgets.(*Spinner).Start()
          /home/simon/src/aerc2/widgets/spinner.go:46 +0x8f
      git.sr.ht/~sircmpwn/aerc2/widgets.NewDirectoryList()
          /home/simon/src/aerc2/widgets/dirlist.go:37 +0x286
      git.sr.ht/~sircmpwn/aerc2/widgets.NewAccountView()
          /home/simon/src/aerc2/widgets/account.go:50 +0x5ca
      git.sr.ht/~sircmpwn/aerc2/widgets.NewAerc()
          /home/simon/src/aerc2/widgets/aerc.go:60 +0x800
      main.main()
          /home/simon/src/aerc2/aerc.go:65 +0x33e

To fix this, introduce a new type, Invalidatable, which protects the field.
Unfortunately the Drawable must be passed to the callback function in
Invalidate, so we still need to re-implement this in each Invalidatable user.
2019-04-27 14:30:28 -04:00

90 lines
1.4 KiB
Go

package widgets
import (
"sync/atomic"
"time"
"github.com/gdamore/tcell"
"git.sr.ht/~sircmpwn/aerc2/lib/ui"
)
var (
frames = []string{
"[..] ",
" [..] ",
" [..] ",
" [..] ",
" [..]",
" [..] ",
" [..] ",
" [..] ",
}
)
type Spinner struct {
ui.Invalidatable
frame int64 // access via atomic
stop chan struct{}
}
func NewSpinner() *Spinner {
spinner := Spinner{
stop: make(chan struct{}),
frame: -1,
}
return &spinner
}
func (s *Spinner) Start() {
if s.IsRunning() {
return
}
atomic.StoreInt64(&s.frame, 0)
go func() {
for {
select {
case <-s.stop:
atomic.StoreInt64(&s.frame, -1)
s.stop <- struct{}{}
return
case <-time.After(200 * time.Millisecond):
atomic.AddInt64(&s.frame, 1)
s.Invalidate()
}
}
}()
}
func (s *Spinner) Stop() {
if !s.IsRunning() {
return
}
s.stop <- struct{}{}
<-s.stop
s.Invalidate()
}
func (s *Spinner) IsRunning() bool {
return atomic.LoadInt64(&s.frame) != -1
}
func (s *Spinner) Draw(ctx *ui.Context) {
if !s.IsRunning() {
s.Start()
}
cur := int(atomic.LoadInt64(&s.frame) % int64(len(frames)))
ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', tcell.StyleDefault)
col := ctx.Width()/2 - len(frames[0])/2 + 1
ctx.Printf(col, 0, tcell.StyleDefault, "%s", frames[cur])
}
func (s *Spinner) Invalidate() {
s.DoInvalidate(s)
}