bar.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package main
  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. func NewScreenBar(title string) *ScreenBar {
  22. bar := new(ScreenBar)
  23. bar.title = title
  24. bar.ticks = 0
  25. bar.tickerActive = true
  26. bar.ticker = time.NewTicker(time.Second)
  27. bar.update()
  28. // Goroutine to handle ticker updates
  29. go func() {
  30. for range bar.ticker.C {
  31. bar.ticks += 1
  32. bar.update()
  33. }
  34. }()
  35. return bar
  36. }
  37. // (Re)paint a screen by drawing bar
  38. func (bar *ScreenBar) update() {
  39. // Config size if in terminal
  40. if term.IsTerminal(0) {
  41. bar.columns, _, _ = term.GetSize(0)
  42. }
  43. // Go home and draw (type) a bar
  44. fmt.Print("")
  45. fmt.Print("")
  46. s := fmt.Sprintf(" %%%ds %%6d ", 10-bar.columns)
  47. fmt.Printf(s, bar.title, bar.ticks)
  48. fmt.Print("")
  49. // An attempt to display Screenbar button using kitty image protocol
  50. 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))
  51. if out, err := cmd.Output(); err != nil {
  52. os.Stdout.Write(out)
  53. log.Print(err)
  54. } else {
  55. os.Stdout.Write(out)
  56. }
  57. }
  58. // Set title visible on the bar
  59. func (bar *ScreenBar) setTitle(msg *osc.Message) {
  60. for _, arg := range msg.Arguments {
  61. switch arg.(type) {
  62. case string:
  63. bar.title = arg.(string)
  64. bar.update()
  65. }
  66. }
  67. }
  68. // Ticker's gonna tick
  69. func (bar *ScreenBar) tick() {
  70. bar.ticks += 1
  71. bar.update()
  72. }
  73. // Ticker's gonna need to be reset sometimes
  74. func (bar *ScreenBar) reset(msg *osc.Message) {
  75. bar.ticks = 0
  76. bar.ticker.Reset(time.Second)
  77. bar.update()
  78. }