Debian Codegraph @

app/spinner.go

raw
1 package app
2
3 import (
4 "strings"
5 "sync/atomic"
6 "time"
7
8 "git.sr.ht/~rjarry/aerc/config"
9 "git.sr.ht/~rjarry/aerc/lib/log"
10 "git.sr.ht/~rjarry/aerc/lib/ui"
11 "go.rockorager.dev/vaxis"
12 )
13
14 type Spinner struct {
15 frame int64 // access via atomic
16 frames []string
17 interval time.Duration
18 stop chan struct{}
19 style vaxis.Style
20 }
21
22 func NewSpinner(uiConf *config.UIConfig) *Spinner {
23 spinner := Spinner{
24 stop: make(chan struct{}),
25 frame: -1,
26 interval: uiConf.SpinnerInterval,
27 frames: strings.Split(uiConf.Spinner, uiConf.SpinnerDelimiter),
28 style: uiConf.GetStyle(config.STYLE_SPINNER),
29 }
30 return &spinner
31 }
32
33 func (s *Spinner) Start() {
34 if s.IsRunning() {
35 return
36 }
37
38 atomic.StoreInt64(&s.frame, 0)
39
40 go func() {
41 defer log.PanicHandler()
42
43 for {
44 select {
45 case <-s.stop:
46 atomic.StoreInt64(&s.frame, -1)
47 s.stop <- struct{}{}
48 return
49 case <-time.After(s.interval):
50 atomic.AddInt64(&s.frame, 1)
51 ui.Invalidate()
52 }
53 }
54 }()
55 }
56
57 func (s *Spinner) Stop() {
58 if !s.IsRunning() {
59 return
60 }
61
62 s.stop <- struct{}{}
63 <-s.stop
64 s.Invalidate()
65 }
66
67 func (s *Spinner) IsRunning() bool {
68 return atomic.LoadInt64(&s.frame) != -1
69 }
70
71 func (s *Spinner) Draw(ctx *ui.Context) {
72 if !s.IsRunning() {
73 s.Start()
74 }
75
76 cur := int(atomic.LoadInt64(&s.frame) % int64(len(s.frames)))
77
78 ctx.Fill(0, 0, ctx.Width(), ctx.Height(), ' ', s.style)
79 col := ctx.Width()/2 - len(s.frames[0])/2 + 1
80 ctx.Printf(col, 0, s.style, "%s", s.frames[cur])
81 }
82
83 func (s *Spinner) Invalidate() {
84 ui.Invalidate()
85 }