Silly little cli celebration tool
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

term.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package yay
  2. import (
  3. "log"
  4. "time"
  5. "github.com/nsf/termbox-go"
  6. )
  7. func init() {
  8. log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
  9. }
  10. type Animation interface {
  11. Next() []rune
  12. }
  13. type ViewPort struct {
  14. viewX, viewY int
  15. vcenter int
  16. hcenter int
  17. timeout time.Duration
  18. animation Animation
  19. }
  20. func NewViewPort(a Animation, to time.Duration) *ViewPort {
  21. vp := &ViewPort{
  22. animation: a,
  23. timeout: to,
  24. }
  25. return vp
  26. }
  27. func (tb *ViewPort) Run() {
  28. err := termbox.Init()
  29. if err != nil {
  30. log.Fatal(err)
  31. }
  32. defer termbox.Close()
  33. tb.viewX, tb.viewY = termbox.Size()
  34. tb.vcenter = tb.viewY / 2.0
  35. tb.hcenter = tb.viewX / 2.0
  36. events := make(chan termbox.Event)
  37. go func() {
  38. for {
  39. events <- termbox.PollEvent()
  40. }
  41. }()
  42. termbox.HideCursor()
  43. func() {
  44. tick := time.Tick(tb.timeout)
  45. for {
  46. termbox.Clear(termbox.ColorBlack, termbox.ColorBlack)
  47. tb.draw()
  48. err := termbox.Flush()
  49. if err != nil {
  50. log.Fatal(err)
  51. }
  52. select {
  53. case <-tick:
  54. case event := <-events:
  55. switch event.Type {
  56. case termbox.EventKey:
  57. switch event.Key {
  58. case termbox.KeyCtrlZ, termbox.KeyCtrlC:
  59. log.Printf("exiting ...")
  60. return
  61. }
  62. switch event.Ch {
  63. case 'q':
  64. return
  65. }
  66. case termbox.EventResize:
  67. tb.viewX, tb.viewY = event.Width, event.Height
  68. tb.vcenter = tb.viewY / 2.0
  69. tb.hcenter = tb.viewX / 2.0
  70. case termbox.EventError:
  71. log.Fatalf("Quitting because of termbox error: \n%s\n", event.Err)
  72. }
  73. }
  74. }
  75. }()
  76. }
  77. func (tb *ViewPort) draw() {
  78. curFrame := tb.animation.Next()
  79. width := len(curFrame) / 2
  80. for i, r := range curFrame {
  81. termbox.SetCell(
  82. tb.hcenter-width+i,
  83. tb.vcenter,
  84. r,
  85. termbox.ColorWhite|termbox.AttrBold, termbox.ColorBlack,
  86. )
  87. }
  88. }