My mirror of the Barnard terminal client for Mumble.
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.

93 lines
1.6 KiB

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