bar.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package bar
  2. import (
  3. "fmt"
  4. "log"
  5. "os"
  6. "os/exec"
  7. "time"
  8. // bar
  9. "golang.org/x/term"
  10. // osc
  11. "github.com/hypebeast/go-osc/osc"
  12. )
  13. // Your basic screenbar
  14. type ScreenBar struct {
  15. title string
  16. ticks int
  17. ticker *time.Ticker
  18. tickerActive bool
  19. columns int
  20. }
  21. // ScreenBar construction
  22. func NewScreenBar(title string) *ScreenBar {
  23. bar := new(ScreenBar)
  24. bar.title = title
  25. bar.ticks = 0
  26. bar.tickerActive = true
  27. bar.ticker = time.NewTicker(time.Second)
  28. bar.update()
  29. // Goroutine to handle ticker updates
  30. go func() {
  31. for range bar.ticker.C {
  32. bar.ticks += 1
  33. bar.update()
  34. }
  35. }()
  36. return bar
  37. }
  38. // (Re)paint a screen by drawing bar
  39. func (bar *ScreenBar) update() {
  40. // Config size if in terminal
  41. if term.IsTerminal(0) {
  42. bar.columns, _, _ = term.GetSize(0)
  43. }
  44. // Go home and draw (type) a bar
  45. fmt.Print("")
  46. fmt.Print("")
  47. s := fmt.Sprintf(" %%%ds %%6d ", 10-bar.columns)
  48. fmt.Printf(s, bar.title, bar.ticks)
  49. fmt.Print("")
  50. // An attempt to display Screenbar button using kitty image protocol
  51. cmd := exec.Command("sh", "-c", fmt.Sprintf("kitten icat -z -1 -n --place 2x1@%dx0 --stdin no images/bar_button.png < /dev/null > /dev/tty", bar.columns))
  52. if out, err := cmd.Output(); err != nil {
  53. os.Stdout.Write(out)
  54. log.Print(err)
  55. } else {
  56. os.Stdout.Write(out)
  57. }
  58. }
  59. // Set title visible on the bar
  60. func (bar *ScreenBar) setTitle(msg *osc.Message) {
  61. for _, arg := range msg.Arguments {
  62. switch arg.(type) {
  63. case string:
  64. bar.title = arg.(string)
  65. bar.update()
  66. }
  67. }
  68. }
  69. // Ticker's gonna tick
  70. func (bar *ScreenBar) tick() {
  71. bar.ticks += 1
  72. bar.update()
  73. }
  74. // Ticker's gonna need to be reset sometimes
  75. func (bar *ScreenBar) reset(msg *osc.Message) {
  76. bar.ticks = 0
  77. bar.ticker.Reset(time.Second)
  78. bar.update()
  79. }