My mirror of the Barnard terminal client for Mumble.

94 line
1.6 KiB

  1. package uiterm
  2. import (
  3. "strings"
  4. "unicode/utf8"
  5. "github.com/nsf/termbox-go"
  6. )
  7. type InputFunc func(ui *Ui, textbox *Textbox, text string)
  8. type Textbox struct {
  9. Text string
  10. Fg Attribute
  11. Bg Attribute
  12. Input InputFunc
  13. ui *Ui
  14. active bool
  15. x0, y0, x1, y1 int
  16. }
  17. func (t *Textbox) uiInitialize(ui *Ui) {
  18. t.ui = ui
  19. }
  20. func (t *Textbox) setBounds(x0, y0, x1, y1 int) {
  21. t.x0 = x0
  22. t.y0 = y0
  23. t.x1 = x1
  24. t.y1 = y1
  25. }
  26. func (t *Textbox) setActive(active bool) {
  27. t.active = active
  28. }
  29. func (t *Textbox) draw() {
  30. var setCursor = false
  31. reader := strings.NewReader(t.Text)
  32. for y := t.y0; y < t.y1; y++ {
  33. for x := t.x0; x < t.x1; x++ {
  34. var chr rune
  35. if ch, _, err := reader.ReadRune(); err != nil {
  36. if t.active && !setCursor {
  37. termbox.SetCursor(x, y)
  38. setCursor = true
  39. }
  40. chr = ' '
  41. } else {
  42. chr = ch
  43. }
  44. termbox.SetCell(x, y, chr, termbox.Attribute(t.Fg), termbox.Attribute(t.Bg))
  45. }
  46. }
  47. }
  48. func (t *Textbox) keyEvent(mod Modifier, key Key) {
  49. redraw := false
  50. switch key {
  51. case KeyCtrlC:
  52. t.Text = ""
  53. redraw = true
  54. case KeyEnter:
  55. if t.Input != nil {
  56. t.Input(t.ui, t, t.Text)
  57. }
  58. t.Text = ""
  59. redraw = true
  60. case KeySpace:
  61. t.Text = t.Text + " "
  62. redraw = true
  63. case KeyBackspace:
  64. case KeyBackspace2:
  65. if len(t.Text) > 0 {
  66. if r, size := utf8.DecodeLastRuneInString(t.Text); r != utf8.RuneError {
  67. t.Text = t.Text[:len(t.Text)-size]
  68. redraw = true
  69. }
  70. }
  71. }
  72. if redraw {
  73. t.draw()
  74. termbox.Flush()
  75. }
  76. }
  77. func (t *Textbox) characterEvent(chr rune) {
  78. t.Text = t.Text + string(chr)
  79. t.draw()
  80. termbox.Flush()
  81. }