bar.go 1.7 KB

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