Skip to content

Commit

Permalink
Add a throbber
Browse files Browse the repository at this point in the history
  • Loading branch information
hjr265 committed Jan 30, 2023
1 parent 3f5c8f7 commit 0009ccc
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type ConfigPrintd struct {
DelayAfter time.Duration
DelayError time.Duration
LogColor bool
Throbber bool
}

func (c *ConfigPrintd) initDefaults() {
Expand All @@ -47,6 +48,7 @@ func (c *ConfigPrintd) initDefaults() {
c.DelayAfter = 500 * time.Millisecond
c.DelayError = 5 * time.Second
c.LogColor = true
c.Throbber = true
}

type ConfigPrinter struct {
Expand Down
12 changes: 12 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ var (
)

func main() {
log.SetPrefix("\033[2K\r")

fmt.Println(` ____ _ _ _
| _ \ _ __(_)_ __ | |_ __| |
` + " | |_) | '__| | '_ \\| __/ _` |" + `
Expand Down Expand Up @@ -52,6 +54,11 @@ func main() {
pulseLoop(cfg, exitch)
}()

throbber := Throbber{}
if cfg.Printd.Throbber {
go throbber.Loop(cfg, exitch)
}

wg.Add(1)
go func() {
defer wg.Done()
Expand All @@ -61,16 +68,21 @@ func main() {
for {
pr, err := getNextPrint(ctx, cfg)
if errors.As(err, &tophError{}) {
throbber.SetState(ThrobberOffline)
log.Println(color.RedString("[E]"), err)
delay = cfg.Printd.DelayError
goto retry
}
catch(err)

if pr.ID == "" {
throbber.SetState(ThrobberReady)
delay = 5 * time.Second
goto retry
}

throbber.SetState(ThrobberPrinting)

log.Printf("[i]"+" Printing %s", pr.ID)
err = runPrintJob(ctx, cfg, pr)
catch(err)
Expand Down
62 changes: 62 additions & 0 deletions throbber.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package main

import (
"fmt"
"log"
"strings"
"sync"
"time"

"github.com/fatih/color"
)

type Throbber struct {
state ThrobberState
m sync.Mutex
}

func (t *Throbber) SetState(s ThrobberState) {
t.m.Lock()
t.state = s
t.m.Unlock()
}

func (t *Throbber) Loop(cfg Config, exitch chan struct{}) {
pad := strings.Repeat(" ", 20)
L:
for i := 0; ; i = (i + 1) % 10 {
var s string
t.m.Lock()
switch t.state {
case ThrobberReady:
b := []byte{' '}
if i < 5 {
b[0] = '~'
}
s = color.GreenString("[" + string(b) + "]")
s += " Ready"
case ThrobberPrinting:
s = color.BlueString("[~]")
s += " Printing"
case ThrobberOffline:
s = color.RedString("[!]")
s += " Offline"
}
t.m.Unlock()
fmt.Fprintf(log.Default().Writer(), "\033[2K\r%s%s\r", pad, s)

select {
case <-exitch:
break L
case <-time.After(125 * time.Millisecond):
}
}
}

type ThrobberState int

const (
ThrobberReady ThrobberState = iota
ThrobberPrinting
ThrobberOffline
)

0 comments on commit 0009ccc

Please sign in to comment.